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.

  1. // This snippet returns TRUE if the node, term page or other page we are
  2. // currently viewing is tagged with a term which belongs
  3. // to the 'desired_vocab' and we are not in edit mode (arg(2)).
  4.  
  5. $vid = 11; // the vocabulary ID you're interested in
  6. $page = 'drupal'; // and/or a page
  7.  
  8. $match = FALSE;
  9.  
  10. //first check if the node is in the vocab
  11. if ( arg(0) == 'node' and is_numeric(arg(1)) and arg(2) == FALSE ) {
  12. // Yes, we're viewing a node in view mode.
  13.  
  14. $node = node_load(arg(1)); // cached
  15. // If the term does not exist we're done
  16. if (is_array($node->taxonomy)) {
  17. foreach ($node->taxonomy as $term) {
  18. if ($term->vid == $vid) {
  19. //return TRUE;
  20. $match = TRUE;
  21. }
  22. }
  23. }
  24. }
  25.  
  26.  
  27. // if above does not match true then check if this is a term page that belongs to the vocab
  28. if($match!=TRUE){
  29. if (arg(0) == 'taxonomy' && arg(1) == 'term') {
  30. $str_tids = arg(2);
  31. $terms = taxonomy_get_tree($vid);
  32. foreach ( $terms as $term ) {
  33. $items[] = $term->tid;
  34. }
  35.  
  36. $terms = taxonomy_terms_parse_string($str_tids);
  37.  
  38. //browse each value
  39. foreach ($terms['tids'] as $k => $v) {
  40. if (in_array($v, $items)) {
  41. $match = TRUE;
  42. }
  43. }
  44. }else{ //finally check is this is the specific page declared in $page
  45. if(strstr($_SERVER['REQUEST_URI'], $page)){
  46. $match = TRUE;
  47. }
  48. }
  49. }
  50. return $match;

Comments

Hi There for some reason this brings up error when used in a block of taxonomy terms. arg2 fails

Add new comment