PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, December 28, 2021

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

 December 28, 2021     custom-wordpress-pages, php, taxonomy-terms, wordpress, wordpress-theming     No comments   

Issue

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>

enter image description here


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
}


Answered By - Ruvee
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing