最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

categories - Count tags for a specific category

programmeradmin0浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论