统计有多少帖子有指定的标签和类别

时间:2020-05-26 作者:JoBe

我知道如何计算有多少帖子有某个标签或类别

例如:

$term_slug = \'some-post-tag\';
$term = get_term_by(\'slug\', $term_slug, $post_tag);
echo $term->count;
BUT!有没有办法统计有多少贴子有标签AND 指定类别?

我想统计一下有多少帖子有标签(slug)“cat”和类别slug“allowpost”

这可能吗?

编辑:如果可能的话,如果可以通过类似于我的第一个脚本的解决方案进行管理,这将是一件好事,因为这将用于搜索结果页面,并且different post pages, 因此,向循环本身添加一些内容是行不通的。。

2 个回复
最合适的回答,由SO网友:JoBe 整理而成

这解决了我的问题,最初由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);

SO网友:Michelle

您可以使用WP\\u查询,特别是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();