仅针对特定自定义帖子类型的自定义分类学计数



我想根据特定的自定义帖子类型显示自定义分类学的计数。目前,我正在使用get_terms列出分类法的所有条款。分类法被多个帖子类型使用。因此,计数器显示了每种帖子类型的分类法的所有用法。

有没有办法限制单个帖子类型的计数?

这是我的实际代码:

get_terms(array(
    'taxonomy'      => 'tax',
    'hide_empty'    => true,
    'orderby'       => 'count',
    'order'         => 'DESC',
    'number'        => '10',
));

foreach内,我正在使用term->count显示使用计数器。

我不建议使用 get_terms,因为这返回分类法的所有条款,而不是与帖子相关的所有条款。

替代解决方案是使用get_posts,在此处阅读更多信息https://developer.wordpress.org/reference/functions/get_posts/

$my_posts = get_posts(array(
  'post_type' => 'post', //post type
  'numberposts' => -1,
  'tax_query' => array(
    array(
      'taxonomy' => 'tax', //taxonomy name
      'field' => 'id', //field to get
      'terms' => 1, //term id
    )
  )
));

然后您可以计算返回的帖子数:

$count = count($my_posts);

我认为以下链接对更好的理解更有帮助。链接

这是为您服务的代码。

$args = array(
    'post_type'      => 'Your_custom_post_type',//Your custom post type here.
    'tax_query'      => array(
        array(
            'taxonomy' => 'Your_taxonomy',//Your taxonomy is here.
            'field' => 'slug',
        )
    )
);

现在我们print_r $args,以更好地理解我们得到的。

_e('<pre>');
print_r($args);
_e('</pre>');

只需查询

$your_query = new WP_Query( $args );

最新更新