WordPress: display the total number of posts on the current category

WordPress: display the total number of posts on the current category

How to get and display the post count on each WordPress category.

Let's say that we want to display the total number of posts contained within each category on the corresponding category page (handled by the category.php theme file). What we need is the current category ID and the WordPress get_category() function. Follow me.

We can get the current category ID from the query variable of the $wp_query object. Done that, we loop through the array of objects returned by the get_category() function and we compare our ID with the cat_ID property of each object. If there's a match, then we're sure that we're on the same category. Therefore we can get the category_count property to know the number of posts associated with the current category.

Add the following code to your functions.php file:

function display_current_category_post_count() {

	$count = '';

	if(is_category()) {
	
		global $wp_query;
		$cat_ID = get_query_var('cat');
		$categories = get_the_category();
		
		foreach($categories as $cat) {
		
			$id = $cat->cat_ID;
			
			if($id == $cat_ID) {
			
				$count = $cat->category_count;
			
			
			}
		
		
		}

	
	
	}

	return $count;
}

Then you can use this function on your category.php file:

<p><?php echo display_current_category_post_count();?> posts.</p>

And here's the result:

[caption id="attachment_1914" align="aligncenter" width="615" caption="The number of posts displayed on each category."]The number of posts displayed on each category.[/caption]