I’ve a situation where I cannot get correct post count from category… and I’ve tried everything but customizing wp_list_categories with walker.
So I’ve category hierarchy:
cat1
cat2 (total 8)
cat3 (total 5)
cat4 (total 3)
All posts are under cat2 and cat3-cat4. I’m displaying cat1 and want to show post count.
If I use following function:
function wp_get_postcount($id) {
//return count of post in category child of ID 15
$count = 0;
$taxonomy = 'category';
$args = array('child_of' => $id);
$tax_terms = get_terms($taxonomy,$args);
foreach ($tax_terms as $tax_term) {
$count +=$tax_term->count;
}
return $count;
}
I get total count of 16. Which is double the real amount, obviously counting twice.
Before this I tried:
$children_cats = get_categories(array(
'hide_empty' => 0,
'taxonomy' => 'category',
));
And used foreach on array and echoing out count. But it would return 0, obviously because parent cat has no posts selected under it…
wp_list_categories actually displays correct value. But I wasn’t able to extend it with walked so I would get my complicated html:
<li>
<a class="subcatimg" href="https://wordpress.stackexchange.com/questions/90344/<?php echo $cat_link; ?>"><?php if (function_exists('get_cat_icon_lite')) echo get_cat_icon_lite( $child->cat_ID );?><span><?php _e('Show All','medishop'); ?></span></a>
<h4><a href="https://wordpress.stackexchange.com/questions/90344/<?php echo $cat_link; ?>"><?php echo $child->name; ?></a></h4>
<p><span><?php echo wp_get_postcount($child->cat_ID); ?></span> <?php _e('products in this category','medishop'); ?></p>
</li>
I’m really out of options. Any advice?