Link a Drupal Image Field to the destination of a Link Field

By default, Drupal’s image fields don’t allow to dynamically link them to the path set inside another field. There are module to tackle this such as Image Link Formatter and Link Image Field.

I prefer keeping display settings in code. It’s really easy to wrap any Image Field with the destination of a Link Field of your choice inside a node template using l() the function:

// If there's an image and a link we wrap the link around it
if($field_pub_bild && $field_pub_link) {
  $linked_image = l(render($content['field_pub_bild']), $field_pub_link[0]['url'], array('html'=> TRUE, 'attributes' => array('target' => '_blank')));

Just make sure you set html to TRUE, otherwise the image tag will get escaped. For further options look at the documentation of the l() function:!

Leave a Reply