Drupal - 显示当前术语的子术语,仅当子项存在时 - 需要修改代码

时间:2013-05-29 16:41:53

标签: drupal drupal-taxonomy

为了解决在一个区块中显示给定分类术语的子术语的问题,我终于偶然发现了一段完全符合我想要的代码here

根据说明我已将以下内容添加到我的template.php

function themename_child_terms($vid = 1) {
  if(arg(0) == 'taxonomy' && arg(1) == 'term') {   
    $children = taxonomy_get_children(arg(2), $vid);
      if(!$children) {
        $custom_parent = taxonomy_get_parents(arg(2));
          $parent_tree = array();
          foreach ($custom_parent as $custom_child => $key) {
            $parent_tree = taxonomy_get_tree($vid, $key->tid);
          }
          $children = $parent_tree;
      }

    $output = '<ul>';
    foreach ($children as $term) {
      $output .= '<li>';
      $output .= l($term->name, 'taxonomy/term/' . $term->tid);
      $output .= '</li>';
    }
    $output .= '</ul>';

    return $output;
  }
}

然后我创建了一个块并添加了:

<?php // $vid is the vocabulary id.
    print themename_child_terms($vid = 1);
?>

这完美地显示了当前术语的子术语。但是,即使没有使用该术语的内容,它也会显示父术语下存在的所有术语。

e.g。 查看第1学期中所有项目的页面,我得到了

孩子1   孩子2
  孩子3

在块中正确列出。但是,如果没有标记为'child 3'的内容,例如,它仍然会在块中显示该术语。这不是很有用,因为它链接到空术语页面。 如何修改代码以仅显示实际上具有与之关联的项目的子项。因此,如果没有标记为“Child 3”的孩子,那么该术语就不会显示出来。这是一个简单的修改吗?

感谢您的任何解决方案。

尼克

使用Drupal 6

1 个答案:

答案 0 :(得分:0)

感谢用户jerdiggity在drupal.stackexchange here上发布以下回复。完美的工作。


嗯......我会尝试这样的事情:

更改代码的这一部分:

foreach ($children as $term) {
  $output .= '<li>';
  $output .= l($term->name, 'taxonomy/term/' . $term->tid);
  $output .= '</li>';
}

这样的事情:

// Avoid unnecessary "Invalid foreach" errors showing up in the log:
if (!empty($children)) {
  // If not empty, run the foreach loop:
  foreach ($children as $term) {
    // Then check to see if any nodes exist for that term id:
    $number_of_nodes = taxonomy_term_count_nodes($term->tid);
    // If there ARE nodes...
    if ($number_of_nodes > 0) {
      // ... then add them to the output:
      $output .= '<li>';
      $output .= l($term->name, 'taxonomy/term/' . $term->tid);
      $output .= '</li>';
    }
  }
}

希望有帮助......:)