【问题标题】:Show children of custom taxonomy terms显示自定义分类术语的子项
【发布时间】:2018-06-16 14:11:29
【问题描述】:

我有 WP Jb 管理器插件,我认为它只是用于工作的自定义帖子类型。我已启用类别创建了一些类别。

我只需要显示每个类别的子类别,而不是整个类别列表。

我有以下代码:

<?php
$terms = get_terms( 'job_listing_category', 'orderby=count&hide_empty=0' );
$count = count($terms);
if ( $count > 0 ){
 echo "<ul>";
 foreach ( $terms as $term ) {
   echo "<li>" . $term->name . "</li>";

 }
 echo "</ul>";
}
?>

这样输出所有类别(父级和子级)的列表:

  • 办公室
  • 仓库
  • 制造
  • 工业
  • 建筑
  • 建筑服务工程师

父类别是粗体类别:办公室、工业和建筑。我想取其中一个并仅显示该类别的孩子。

例如:get_category('industrial', 'children_of')(我知道这不是正确的语法),所以它会导致只显示工业类别的孩子:

  • 仓库
  • 制造

我似乎找不到办法做到这一点 - 有人可以帮忙吗?

【问题讨论】:

    标签: php wordpress custom-post-type custom-taxonomy


    【解决方案1】:

    我通过使用以下代码设法做到了这一点:

    <?php
    $terms = get_terms( 'job_listing_category', 'parent=59' );
    $count = count($terms);
    if ( $count > 0 ){
     echo "<ul>";
     foreach ( $terms as $term ) {
       echo "<li>" . $term->name . "</li>";
    
     }
     echo "</ul>";
    }
    ?>
    

    【讨论】:

      【解决方案2】:

      您可以获取父类别,然后为每个子类别构建一个列表,如下所示:

      <?php
      $taxonomies = get_terms(array(
          'taxonomy' => 'job_listing_category',
          'hide_empty' => false,
          'parent' => 0,
      ));
      
      if (!empty($taxonomies)):
          foreach ($taxonomies as $parent) {
              $output = '<ul>';
              $children = get_terms(array(
                  'taxonomy' => 'job_listing_category',
                  'parent' => $parent->term_id,
                  'hide_empty' => false,
              ));
              foreach ($children as $child) {
                  $output .= '<li>' . esc_html($child->name) . '</li>';
              }
              $output = '</ul>';
          }
          echo $output;
      endif;
      

      请注意,代码未经测试。在此处查找更多信息:https://developer.wordpress.org/reference/functions/get_terms/

      【讨论】:

      • 非常感谢 - 但是它似乎没有输出任何东西。我不确定这是否重要,但这段代码用于主页......我从数组中最后一项的末尾删除了逗号(我认为他们不需要在那里,但我仍然没有害怕
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      相关资源
      最近更新 更多