Print Friendly and PDF

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.

has written 246 posts

Hey there! This is the place where I write about the technology I understand. Personally I'm a geek and professionally Web Developer. You can also check my other site to get to know about my other hobbies ;)

Swashata has another home at http://www.swashata.com/

Comments Feed

TOP

5 Responses

Comment Now

  1. Hi Swashata, Thanks for the code snippet. You have a nice blog especially i like the top bar very much ;)

  2. 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. Sweet!. Just what i was looking for… Thanks alot.

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

  4. Great site…, great article…., thanks a lot Swashata. This function really helped me

Leave a Reply

Trackbacks/Pingbacks

Trackback URL

No trackbacks yet! If you wish, you can trackback this post from the above link