So I have a simple code that gets the tags and counts them. How would I limit this code to count how many posts are tagged but only include those posts that belong to a specific category? Right now, my code counts every single post on the website.

$terms = get_terms( array(
'taxonomy' => 'post_tag',
'hide_empty' => true,
'orderby' => 'ID',
    ) );
foreach($terms as $t) {
echo  '<div class="btn btn-info btn-sm ml-2">' .$t->name. ' <span class="badge badge-light">' .$t->count. '</span>

1 Answer 1


count how many posts are tagged but only include those posts that belong to a specific category

You can't do that via get_terms(), but you can make a WP_Query query and use the $found_posts property to get the total posts.

So for example, in your foreach, you can use the tag and cat parameters like so — just change the 1,23 with the correct category ID(s):

$query = new WP_Query( array(
    'tag'            => $t->slug,
    'cat'            => '1,23', // category ID(s)
    'fields'         => 'ids',
    'posts_per_page' => 1,
) );

$count = $query->found_posts; // the total posts

Note: I used 'fields' => 'ids' and 'posts_per_page' => 1 because I just wanted to know the total posts, hence I don't need the full post data and I also set the posts per page to only 1.

And please check the documentation for more information on the parameters and other details.

  • I appreciate the answer but I see now that I wasn't completely clear in what my goal is. I'm trying to count how many posts are tagged with something, but only look at the posts that belong to a certain category. I use same tags across different categories, and was just thinking whether it was possible to add an argument that would limit the count to a particular category.
    – Dan
    Dec 5, 2020 at 12:08
  • I hope you don't mind I changed my answer completely, and hopefully this time I got it right.. :)
    – Sally CJ
    Dec 5, 2020 at 15:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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