drupaldrupal-7drupal-taxonomydrupal-templates

Adding conditions to a view template file in Drupal


I need to add a condition to a button hard-coded into the template file in a Drupal 7 theme. I would like the 'compare' button only to appear on the node pages of products that have certain taxonomy terms attached to them. I guess, it could be done with a simple IF, but I'm not a developer and only know the very basics of PHP syntax, so I would be really grateful, if someone could describe in detail how to implement a solution, perhaps even provide a snippet of code that I can customize and paste in the right place!

<div class="actions">
    <?php print flag_create_link('wishlist', $node->nid); ?>
    <?php print flag_create_link('compare', $node->nid); ?>
  </div><!-- .actions -->
</div>

This is the section in the code of the node--product.tpl.php file that puts out the action buttons. I would like the second one, the compare button to only appear for nodes that have certain taxonomy terms.

Thank you in advance!

Huba


Solution

  • You can use the following code.

    <?php
      $display_compare = FALSE; // don't display by default
      $tids = array(1, 2, 3); // array of certain taxonomy terms' tids
    
      foreach ($node->TERM_FIELD_NAME[LANGUAGE_NONE] as $delta => $term) {
        if (in_array($term['tid'], $tids)) {
          $display_compare = TRUE; // display if node has at least one of specified terms
          break;
        }
      }
    
      if ($display_compare) {
        print flag_create_link('compare', $node->nid);
      }
    ?>
    

    Please don't forget to replace "TERM_FIELD_NAME" with your field name and "1, 2, 3" with your list of tids.