Search code examples
phpwordpresswordpress-themingcustom-wordpress-pagestaxonomy-terms

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


I want to count the number of sub-terms under each parent term in WordPress.

I have created a custom taxonomy in WordPress. I would like to display all the terms of this custom taxonomy on a custom page, such as:

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.

The number of posts under each term is being counted. But I'm in trouble with the sub-term.

This is my code.

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

Solution

  • You could use get_term_childrenDocs function to get all of the "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
    }