tags:

views:

158

answers:

1

I'm using imagecache with an image gallery for drupal. When the field is set to an imagecache preset that links to the original image. I want it so that when the preset image is clicked, the original image loads in a new tab. How can I add the target="_blank" attribute to an imagecache preset?

A: 

You need to override the image linked to image field formatter in your theme, which is created by theme_imagecache_formatter_imagelink(). Add this to your theme's template.php:

function mytheme_imagecache_formatter_mypreset_imagelink($element) {
  // Inside a view $element may contain NULL data. In that case, just return.
  if (empty($element['#item']['fid'])) {
    return '';
  }

  // Extract the preset name from the formatter name.
  $presetname = substr($element['#formatter'], 0, strrpos($element['#formatter'], '_'));
  $style = 'imagelink';

  $item = $element['#item'];
  $item['data']['alt'] = isset($item['data']['alt']) ? $item['data']['alt'] : '';
  $item['data']['title'] = isset($item['data']['title']) ? $item['data']['title'] : NULL;

  $imagetag = theme('imagecache', $presetname, $item['filepath'], $item['data']['alt'], $item['data']['title']);
  $path = file_create_url($item['filepath']);
  $class = "imagecache imagecache-$presetname imagecache-$style imagecache-{$element['#formatter']}";
  return l($imagetag, $path, array('attributes' => array('class' => $class, 'target' => '_blank'), 'html' => TRUE));
}

Replace mytheme and mypreset with the short name of your theme and the short name of your preset, respectively. This function is identical to theme_imagecache_formatter_imagelink() except for the last line, which adds the target="_blank" attribute to the link.

Mark Trapp
Sweet! Do I have to define a new function for each preset or is there a way to combine them?
Toxid
As of right now, you have to define a new function for each preset. It should be possible to override `theme_imagecache_formatter_imagelink()` directly with `mytheme_imagecache_formatter_imagelink()`, but Imagecache is using deep magic I don't entirely understand to require the theme function name expansion. Will update my answer when I learn why this is.
Mark Trapp