Category and children post count

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?

7 s
7

Checking Daniel Llewellyn code and WordPress’ WP_Query reference, I realized that we need to pass an array of array within the tax_query parameter. Otherwise, it’d just return all post counts.

Here is the little modified code:

if ( ! function_exists( 'ipt_kb_total_cat_post_count' ) ) :

/**
 * Simple function to get category post count including all subcategories
 *
 * @link http://wordpress.stackexchange.com/a/91551 Stackexchange
 * @param  int $cat_id Category ID
 * @return int         Total post count
 */
function ipt_kb_total_cat_post_count( $cat_id ) {
    $q = new WP_Query( array(
        'nopaging' => true,
        'tax_query' => array(
            array(
                'taxonomy' => 'category',
                'field' => 'id',
                'terms' => $cat_id,
                'include_children' => true,
            ),
        ),
        'fields' => 'ids',
    ) );
    return $q->post_count;
}

endif;

Hope it helps someone like me.

Leave a Comment