get_category_count()

September 21st, 2008

get_category_count() is a Wordpress function to count the posts within a category. It can probably be written in many different ways.
Here is my version of the function and should be placed in functions.php in your theme:

function wt_get_category_count($input = '') {
	global $wpdb;
	if($input == '')
	{
		$category = get_the_category();
		return $category[0]->category_count;
	}
	elseif(is_numeric($input))
	{
		$SQL = "SELECT $wpdb->term_taxonomy.count FROM $wpdb->terms, $wpdb->term_taxonomy WHERE $wpdb->terms.term_id=$wpdb->term_taxonomy.term_id AND $wpdb->term_taxonomy.term_id=$input";
		return $wpdb->get_var($SQL);
	}
	else
	{
		$SQL = "SELECT $wpdb->term_taxonomy.count FROM $wpdb->terms, $wpdb->term_taxonomy WHERE $wpdb->terms.term_id=$wpdb->term_taxonomy.term_id AND $wpdb->terms.slug='$input'";
		return $wpdb->get_var($SQL);
	}
}

It can be called in three different ways…

1. Just call the function within The Loop and it will return the count of the first category within the current post.

<?php echo wt_get_category_count(); ?>

2. Use the function with an ID and it will return the count of the first category within the post ID.

<?php echo wt_get_category_count(1); ?>

3. Use the function with a slug / nicename and it will return the count of the first category within the post slug / nicename.

<?php echo wt_get_category_count('hello-world'); ?>

To get all new functions/template tags, install my plugin WP Extra Template Tags.

  1. 2009-12-25 - mikeamc

    Very nice tip, but when a category is empty the function do not return the zero “0″. Is there a way to resolve that ? thanks a lot

  2. 2009-08-05 - Dominic Desbiens

    Very nice function. Thank you very much. Is it count all posts in sub-cats when you enter a main cat? (parent cat)

  3. 2009-03-02 - Sam Davis

    I have a website dedicated to Magento and I use this feature on my home page.

    However, is it possible to use this function for Link Categories (ie: The number of Blogroll links in a particular cat)?

    Thanks.