如何计算WordPress中每个父术语下的子术语数

How to count the number of sub-terms under each parent term in WordPress

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

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

1. I want to display all sub-terms under each parent term in the loop.
2. I want to count the number of sub-terms under each parent term.

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

这是我的代码。

   <?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>

您可以使用 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
}