Drupal - display blocks according to node's taxonomy term ID

∥☆過路亽.° 提交于 2019-12-24 07:29:15

问题


I'm just trying to restrict block visibility to nodes that have a certain taxonomy ID. I'm using this snippet...:

<?php
  $term_id_to_trigger_show_block = 109;

  if ((arg(0) == 'node') && is_numeric(arg(1))) {
    $terms = taxonomy_node_get_terms(arg(1));
    foreach($terms as $term) {
      if ($term->tid == $term_id_to_trigger_show_block) {
         return TRUE;
      }
    }
  }
?>

...but I get no joy, the block remains hidden on the relevant nodes.

Any ideas?

Cheers


回答1:


It looks like in drupal6 taxonomy_node_get_tree() takes a node rather than a nid.

The easiest way to change your code is:

<?php
  $term_id_to_trigger_show_block = 109;

  if ((arg(0) == 'node') && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $terms = taxonomy_node_get_terms($node);
    foreach($terms as $term) {
      if ($term->tid == $term_id_to_trigger_show_block) {
         return TRUE;
      }
    }
  }
?>

node_load() caches nodes in memory so it won't be a big performance hit.

But wait! you may be able to refine this even further...

menu_get_item() will get the currently loaded menu item when the node object is loaded it will call taxonomy_node_get_terms(). So you can simplify to:

<?php
  $term_id_to_trigger_show_block = 109;
  $object = get_menu_item();

  if (isset($object->taxonomy)) {
    foreach($object->taxonomy as $term) {
      if ($term->tid == $term_id_to_trigger_show_block) {
         return TRUE;
      }
    }
  }
?>

This will get other object types wich have a taxonomy object which could cause some confusion, if so stick the arg(0) == 'node' back in.



来源:https://stackoverflow.com/questions/3193745/drupal-display-blocks-according-to-nodes-taxonomy-term-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!