Get post count of a category including sub-categories in WordPress

get-post-count-from-cat-with-child

get-post-count-from-cat-with-childFrom the title, you probably have guessed what I am going to talk about. In WordPress, we have many APIs to list down the category, but when we use the get_category function, it lacks the ability to show the post counts from its sub or child categories. Whereas, when we use query_posts or get_posts to get posts from a particular category, it returns posts from child categories as well.

I faced this problem, while developing the 2nd version of the WP-CPL plugin. So I came up with a custom function which will return total post counts from the specified category and its child categories (if any).

Here are the codes and the usage instruction.

The Custom Function:

function wp_get_cat_postcount($id) {
	$cat = get_category($id);
	$count = (int) $cat->count;
	$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;
}

Usage Guide:

The usage of this function is pretty straight forward. You call the function whenever you need passing the category id. Say, the category ID is 2. You call it with something like this:

The total number of posts under "My Awesome Category" is <?php echo wp_get_cat_postcount(2); ?>

Well, that’s all. Short and informative. If you have any questions, be sure to drop in using comments.

5 comments

  1. Mr.Ven

    Hi Swashata, Thanks for the code snippet. You have a nice blog especially i like the top bar very much ๐Ÿ˜‰

  2. design agency

    Commenting on other blogs is a great way to get traffic to your blog. Another really good way is to use sites like Stumble Upon. I get 500-800 visitors a day some days just from Stumble Upon.

  3. Brian

    Sweet!. Just what i was looking for… Thanks alot.

    Ohh can only love WordPress and Magento ..:-)…- allwas nice and easy to work with…

Comments are closed.