仅显示列表已发布帖子的列表分类/类别计数

时间:2017-10-26 作者:Carl Alberto

我想在分类法列表上显示相应的发布项目计数。查看WP文档,似乎我几乎可以通过使用get\\u terms函数实现这一点https://developer.wordpress.org/reference/functions/get_terms/ 但我得到了所有的帖子,包括草稿和垃圾。

$taxonomy = \'item_category\';
  $args =  array(
    \'hide_empty\' => false,
    \'orderby\'    => \'name\',
    \'order\'      => \'ASC\'
  );
$terms = get_terms( $taxonomy , $args );

foreach( $terms as $term ) {
  echo $term->name . \' - \' . $term->count . \'<br/>\';
}
WP是否有一个内置的参数来从get\\u terms函数中显示它,因为我在文档中没有看到它?是否有任何其他功能或过滤器,我可以尝试实现我想要的输出?

1 个回复
最合适的回答,由SO网友:Carl Alberto 整理而成

检查了源代码,完成此操作的唯一方法似乎是过滤每个术语的输出计数,您可以通过在get\\u terms调用之前插入此过滤器来实现这一点。请注意,这将始终显示已发布的项目计数,因此请注意其用法。

function get_terms_filter_published( $terms, $taxonomies, $args ) {
  global $wpdb;
  $taxonomy = $taxonomies[0];
  if ( ! is_array($terms) && count($terms) < 1 ) {
    return $terms;
  }

  $filtered_terms = array();
  $ctr = 0;
  foreach ( $terms as $term ) {
    $result = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts p JOIN $wpdb->term_relationships rl ON p.ID = rl.object_id WHERE rl.term_taxonomy_id = $term->term_id AND p.post_status = \'publish\' LIMIT 1");
    $published_terms[ $ctr ] = $term;
    if ( intval($result) > 0 ) {
        $published_terms[ $ctr ] = $term;
    } else {
        // you can comment this out if you don\'t want to show empty terms
        $published_terms[ $ctr ]->count = 0;
    }
    $ctr++;
  }
  return $published_terms;
}

add_filter(\'get_terms\', \'get_terms_filter_published\', 10, 3);

$taxonomy = \'item_category\';
$args =  array(
  \'hide_empty\' => false,
  \'orderby\'    => \'name\',
  \'order\'      => \'ASC\'
);
$terms = get_terms( $taxonomy , $args );

foreach( $terms as $term ) {
  echo $term->name . \' - \' . $term->count . \'<br/>\';
}

结束

相关推荐

Search Media by taxonomy

如何根据前端的分类法搜索媒体?以下查询显示我希望通过搜索返回的内容:$args = array( \'post_type\' => \'attachment\', \'post_status\' => \'inherit\', // for PDFs \'post_mime_type\' => \'application/pdf\', // if you need PDFs from a specific media c