【问题标题】:How to count the number of sub-terms under each parent term in WordPress如何计算WordPress中每个父项下的子项数
【发布时间】:2021-12-28 16:00:01
【问题描述】:

我想统计WordPress中每个父项下的子项数。

我在 WordPress 中创建了一个自定义分类法。我想在自定义页面上显示此自定义分类的所有术语,例如:

1.我想在循环中显示每个父项下的所有子项。
2.我想统计每个父项下的子项数。

正在统计每个术语下的帖子数。但我在子项上遇到了麻烦。

这是我的代码。

   <?php 
      $args = array(
          'taxonomy' => 'pharma',
          'get' => 'all',
          'parent' => 0,
          'hide_empty' => 0
      );
      $terms = get_terms( $args );
      foreach ( $terms as $term ) : ?>
      <div class="single_pharma">
        <h2 class="pharma_name"><a href="<?php echo esc_url( get_term_link( $term ) ); ?>"><?php echo $term->name; ?></a></h2>

        <span class="count_category"><span>Generics:</span><?php // want to display here sub term count  ?></span>

        <span class="count_brand"><span>Brands:</span><?php echo $term->count; ?></span>
      </div>

【问题讨论】:

    标签: php wordpress wordpress-theming custom-wordpress-pages taxonomy-terms


    【解决方案1】:

    您可以使用get_term_childrenDocs 函数来获取所有“sub_terms”:

    $args = array(
        'taxonomy'   => 'pharma',
        'get'        => 'all',
        'parent'     => 0,
        'hide_empty' => 0
    );
    
    $terms = get_terms($args);
    
    foreach ($terms as $term) {
    
        $count_sub_terms = count(get_term_children($term->term_id, 'pharma'));
    
    ?>
        <div class="single_pharma">
            <h2 class="pharma_name"><a href="<?php echo esc_url(get_term_link($term)); ?>"><?php echo $term->name; ?></a></h2>
    
            <span class="count_category"><span>Generics:</span><?php echo $count_sub_terms;  ?></span>
    
            <span class="count_brand"><span>Brands:</span><?php echo $term->count; ?></span>
        </div>
    <?php
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      • 2011-08-07
      • 2018-06-22
      • 1970-01-01
      • 2013-02-28
      • 1970-01-01
      相关资源
      最近更新 更多