Archived topic
Display post count of each subcategory
1 reply · Started by Sebastian on April 12, 2021
Hi, I'm using this code to display a list of subcategories:
ob_start();
$term_id = $atts['id'];
$taxonomy_name = 'category';
$term_children = get_term_children( $term_id, $taxonomy_name );
echo '<ul class="list-subcats">';
foreach ( $term_children as $child ) {
$term = get_term_by( 'id', $child, $taxonomy_name );
echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a></li>';
}
echo '</ul>';
return ob_get_clean();
got the code from here: https://generatepress.com/forums/topic/list-subcategories/
I want to display the post count next to each category name like this: Category(24), how do i do that?
Hi there,
change this line:
echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a></li>';
to:
echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '(' . $term->count . ')</a></li>';
Just a quick note - when adding Code to a support topic, before submitting the the topic/reply - highlight the code and click the Code button in the toolbar. This will preserve the code formatting and stop it from breaking the forum layout :)