Blair Wadman 2 minute read

Block visibility by vocabulary

This snippet should be added in a block under "block visibility". "Show if the following PHP code returns TRUE" should be selected.

It is designed to display the block if the node has a term that belongs to a given vocabulary (specified in the top of the code). It will also show the block on a term page if that term belongs to the given vocabulary. An additional page can be nominated if desired.

The $vid and $page should be adjusted as follows:

$vid = the vocabulary id eg 11 $page = another page that you specify for the block is display on. eg 'drupal'

This is a combination of snippets from this page on drupal: http://drupal.org/node/69076

I will write this up as a blog post to explain everything in detail at a later date.

  // This snippet returns TRUE if the node, term page or other page we are
  // currently viewing is tagged with a term which belongs
  // to the 'desired_vocab' and we are not in edit mode (arg(2)).

  $vid = 11;  // the vocabulary ID you're interested in
  $page = 'drupal'; // and/or a page

  $match = FALSE;

  //first check if the node is in the vocab
  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 ($term->vid == $vid) {
          //return TRUE;
          $match = TRUE;
        }
      }
    }
  }


  // if above does not match true then check if this is a term page that belongs to the vocab
  if($match!=TRUE){
      if (arg(0) == 'taxonomy' && arg(1) == 'term') {
      $str_tids = arg(2);
      $terms = taxonomy_get_tree($vid);
      foreach ( $terms as $term ) {
        $items[] = $term->tid;
      }

      $terms = taxonomy_terms_parse_string($str_tids);

      //browse each value
      foreach ($terms['tids'] as $k => $v) {
        if (in_array($v, $items)) {
          $match = TRUE;
        }
      }
    }else{ //finally check is this is the specific page declared in $page
      if(strstr($_SERVER['REQUEST_URI'], $page)){
        $match = TRUE;
      }
    }
  }
  return $match;