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>
</div>';
}
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>
</div>';
}
Share
Improve this question
edited Dec 5, 2020 at 13:37
Dan
asked Dec 5, 2020 at 10:15
DanDan
431 silver badge8 bronze badges
1 Answer
Reset to default 1count 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.