Community Documentation

Block visibility if node is has 2 or more terms

Last updated April 8, 2008. Created by nevets on April 8, 2008.
Edited by add1sun. Log in to edit this page.

Let's say I only want a block to appear if the node currently being viewed is tagged with two specific terms. In other words, only show if BOTH tags are applied to the current node.

This script is a modification of the snippet for Block visibility by Vocabulary ID. It will return TRUE if all the desired terms are found.

<?php
 
// This snippet returns TRUE if the node we are
  // currently viewing is tagged with all the desired  terms
  // and we are not in edit mode (arg(2)).

  // put here the terms you are interested in the array
  // they must all be found for TRUE to be returned

 
$desired_terms = array(32, 54);
 
$found = 0;

  if (
arg(0) == 'node' and is_numeric(arg(1)) and arg(2) == FALSE ) {
   
// Yes, we're viewing a node in view mode.

   
$node = node_load(arg(1)); // cached
    // If the term does not exist we're done
   
if (is_array($node->taxonomy)) {
      foreach (
$node->taxonomy as $term) {
        if (
in_array($term->tid, $desired_terms) ) {
         
$found++;
        }
      }
      if (
$found == count($desired_terms) ) {
        return
TRUE;
      }
    }
  }
  return
FALSE;
?>

Reference

Drupal’s online documentation is © 2000-2012 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.