【问题标题】:Show count of Custom Taxonomy only for a specific Custom Post Type仅显示特定自定义帖子类型的自定义分类计数
【发布时间】:2018-05-21 18:54:09
【问题描述】:

我想根据特定的自定义帖子类型显示自定义分类的计数。目前,我使用get_terms 列出分类法的所有术语。 分类被多个帖子类型使用。因此,计数器会显示每个帖子类型的分类法的所有使用情况。

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

这是我的实际代码:

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

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

【问题讨论】:

    标签: php wordpress custom-post-type custom-taxonomy


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      我认为以下链接更有助于更好地理解。 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 );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-18
        • 1970-01-01
        • 1970-01-01
        • 2016-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多