"Asegurar su presencia en Internet contribuye"

Drupal 7 taxonomy image links

Imagen de admin
Posted by admin on Dom 11 Dic 2011

Recently upgraded my site to d7 and wanted to have taxonomy images. This is extremely easy in Drupal 7 as you can add CCK fields to taxonomy. Some images used require a link back to the owner's website as a condition of use so I added a link field as well. Here is the taxonomy manage fields screen (goto edit vocabulary from structure, taxonomy):-

drupal 7 taxonomy fields

Note the two additional fields, Image and Link. The xm lsitemap field comes from the xmlsitemap module. On the "Manage Display" tab, I changed the label display to hidden.

If you now view a taxonomy term page, the image and link will display. However, this is not what I wanted. I needed to wrap the image inside the anchor tag to make the image clickable. I guess there are several ways to do this, but I found this worked. I added #pre_render code like this inside a custom module (xxx in this example):-

  1. function xxx_page_alter(&$page) {
  2. $page['content']['system_main']['term_heading']['term']['#pre_render'][] = 'xxx_taxo_image_link';
  3. }
  5. function xxx_taxo_image_link($elements) {
  6. if (isset($elements['field_link']['0']['#markup'])) {
  7. $elements['field_image']['#prefix'] = '<a href="'. $elements['field_link']['0']['#markup'] .'">';
  8. $elements['field_image']['#suffix'] = '</a>';
  9. unset($elements['field_link']);
  10. }
  11. return $elements;
  12. }

The first function adds a call to xxx_taxo_image_link() to the #pre-render array for the term in the heading. The second function makes the image linkable by adding the anchor tag using #prefix and #suffix. The if makes sure the wrapping only occurs if there is link data. The unset ensures the link is removed and not displayed.