admin管理员组文章数量:1334133
I know how to count how many posts has a certain tag, or category
For example:
$term_slug = 'some-post-tag';
$term = get_term_by('slug', $term_slug, $post_tag);
echo $term->count;
BUT! Is there anyway to count how many posts that have a tag AND a specified category?
I want to count how many posts that have the tag(slug) "cat" and the category slug "allowpost"
Is this even possible?
Edit: if possible, it would be good if this is manageable via some solution similarly my first script, because this is going to be used on search result pages, and different post pages, so adding something to the loop itself won't work..
I know how to count how many posts has a certain tag, or category
For example:
$term_slug = 'some-post-tag';
$term = get_term_by('slug', $term_slug, $post_tag);
echo $term->count;
BUT! Is there anyway to count how many posts that have a tag AND a specified category?
I want to count how many posts that have the tag(slug) "cat" and the category slug "allowpost"
Is this even possible?
Edit: if possible, it would be good if this is manageable via some solution similarly my first script, because this is going to be used on search result pages, and different post pages, so adding something to the loop itself won't work..
Share Improve this question edited May 27, 2020 at 6:19 JoBe asked May 26, 2020 at 18:09 JoBeJoBe 1712 silver badges11 bronze badges2 Answers
Reset to default 0You could use WP_Query and specifically a tax_query:
$args = array(
'post_type' => 'post',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( 'allow-list' ),
),
array(
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => array( 'cats' ),
),
),
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
$count = $the_query->found_posts;
echo 'Post count: ' . $count;
// echo '<ul>';
// while ( $the_query->have_posts() ) {
// $the_query->the_post();
// echo '<li>' . get_the_title() . '</li>';
// }
// echo '</ul>';
} else {
echo 'No posts found';
}
/* Restore original Post Data */
wp_reset_postdata();
This solved my issue, originally created by Mr. Prashant Singh @ WordPress forum
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'AND', // only posts that have both taxonomies will return.
array(
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => 'your-tag-slug', //cat
),
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'your-category-slug', //allowpost
),
),
);
$posts = get_posts($args);
$count = count($posts);
本文标签: categoriesCount how many posts have a specified tag AND category
版权声明:本文标题:categories - Count how many posts have a specified tag AND category 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742349524a2458205.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论