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 >
<h2 ><a href="<?php echo esc_url( get_term_link( $term ) ); ?>"><?php echo $term->name; ?></a></h2>
<span ><span>Generics:</span><?php // want to display here sub term count ?></span>
<span ><span>Brands:</span><?php echo $term->count; ?></span>
</div>
CodePudding user response:
You could use get_term_children
Docs 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 >
<h2 ><a href="<?php echo esc_url(get_term_link($term)); ?>"><?php echo $term->name; ?></a></h2>
<span ><span>Generics:</span><?php echo $count_sub_terms; ?></span>
<span ><span>Brands:</span><?php echo $term->count; ?></span>
</div>
<?php
}