WordPress: Hacks for the Media Uploader – Jocha

This code will rewrite the output so that the links will point to the image-file and not to attachment.php (or the attachment page rather). It will also remove the wp-att-xxxx from the rel=”attachment wp-att-xxxx” line, this blocked me from using fancybox.

Add the following code to the functions.php file in your theme.

function image_send_to_editor_rewrite($html, $id, $caption, $title, $align, $url, $size, $alt = '') {
    $html = get_image_tag($id, $alt, $title, $align, $size);
    $rel = $rel ? ' rel="attachment"' : '';
        // get file url
    $src = wp_get_attachment_image_src($id, 'full'); // change size here
    if ( $url )
            // force href to file url $src[0]
    $html = '<a href="' . esc_attr($src[0]) . "\"$rel>$html</a>";
    return $html;
}
add_filter('image_send_to_editor', 'image_send_to_editor_rewrite', 1, 8); 

If you’d like to add properties (classes) to all images uploaded add the code below.
I used this to insert “fancybox” to my images, but it can be used for many different reasons.

function give_linked_images_class($html, $id, $caption, $title, $align, $url, $size, $alt = '' ){
  $classes = 'img'; // separated by spaces, e.g. 'img image-link fancybox'
  // check if there are already classes assigned to the anchor
  if ( preg_match('/<a.*? class=".*?">/', $html) ) {
    $html = preg_replace('/(<a.*? class=".*?)(".*?>)/', '$1 ' . $classes . '$2', $html);
  } else {
    $html = preg_replace('/(<a.*?)>/', '$1 class="' . $classes . '">', $html);
  }
  return $html;
}
add_filter('image_send_to_editor', 'image_send_to_editor_rewrite', 1, 8);

Note that the code above will only change included content after this is deployed, if you inserted pictures to older posts those need to be re-added for this to apply.