In WordPress, how do I get the number of posts next to <?php single_cat_title(''); ?> in the category.php file?

<h1><?php single_cat_title(''); ?> (<?php ????code to count number of posts in the category shown?>?? ?>)</h1>

I figured out how to do it.

This code shows the number of posts on a page after clicking on a category in WordPress. Even if the post has lots of categories.

<?php $category = get_queried_object(); echo $category->count; ?>

I used this code as the code was in the category.php file and not part of the regular loop.

I hope this code helps anyone else if they are having the same type of problem.

| improve this answer | |

You can use the function get_category() to get the category object and then just simply echo the $count property value.

$cat_count = get_category( 'ID OR ROW OBJECT' );
echo $cat_count->count;

If you also want to get the category object or ID before that then use this code:

$categories = get_the_category();
$category_id = $categories[0]->cat_ID;
| improve this answer | |
  • Thank you so much for your reply here. I have a page with posts that look like this: (Title:) Ice Festival (Categories:) Activities, Activity, Cccc, English Post, Events, Hhhh, Lake Ssss, Winter (Excerpt:) Blah blah blah. The problem is each post has about 10 to 20 categories. How would I get the category when it is clicked? – Glen Charles Rowell Feb 18 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.