首页 文章

仅显示特定自定义帖子类型的自定义分类的计数

提问于
浏览
4

我想根据特定的自定义帖子类型显示自定义分类的计数 . 目前,我正在使用 get_terms 列出分类标准的所有条款 . 分类标准由多个邮政类型使用 . 因此,计数器显示每个帖子类型的分类法的所有用法 .

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

这是我的实际代码:

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

foreach 中,我正在使用 term->count 来显示使用计数器 .

2 回答

  • 2

    我不建议使用 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);
    
  • 4

    我认为以下链接更有助于更好地理解 . Link

    这是为您服务的代码 .

    $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 );
    

相关问题