获取定制分类的术语内部没有帖子
问题描述:
如何获得定制分类术语内的帖子数量? (包括附属于子期限的职位)。获取定制分类的术语内部没有帖子
例如我有:
术语(2个)
柴尔德术语(2个)
--child子项(1柱)
现在我是,像这样:
$categories = get_terms($taxonomy,$args);
foreach ($categories as $categ) {
print $categ->name.'/'.$categ->count;
}
但是对于“term”我只有2个帖子,当我真的需要显示5(2个来自“term”和3个来自它的孩子)。
感谢
答
还有就是要做到这一点更简单的方法:做一个标准的WP_Query
with taxonomy parameters:
$args = array(
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => 'your_custom_taxonomy',
'field' => 'slug',
'terms' => 'your-parent-term-name',
),
),
);
$query = new WP_Query($args);
// Get the count
$count = $query->post_count;
如果你不知道姓名(或名称)的分类中的术语,您可以执行查询并将其ID作为数组传递给WP_Query
。有关更多信息,请参阅this post on WPSE。
答
这是我碰上几次,我改变the code from PatchRanger on bountify,使其与分类工作(所以请注意这个解决方案是基于他的作品):
function wp_get_term_postcount($term) {
$count = (int) $term->count;
$tax_terms = get_terms($term->taxonomy, array('child_of' => $term->term_id));
foreach ($tax_terms as $tax_term) {
$count += wp_get_term_postcount_recursive($tax_term->term_id);
}
return $count;
}
function wp_get_term_postcount_recursive($term_id, $excludes = array()) {
$count = 0;
foreach ($tax_terms as $tax_term) {
$tax_term_terms = get_terms($tax_term->name, array(
'child_of' => $tax_term->term_id,
'exclude' => $excludes,
));
$count += $tax_term->count;
$excludes[] = $tax_term->term_id;
$count += wp_get_term_postcount_recursive($tax_term->term_id, $excludes);
}
return $count;
}
的递归功能是为了防止孩子的重复计数。您可以在functions.php中添加这两个函数。
然后更新您的代码使用它:
$categories = get_terms($taxonomy, $args);
foreach($categories as $categ) {
print $categ->name.'/'wp_get_term_postcount($categ);
}
你可能会有更多的运气在[Wordpress Exchange](http://wordpress.stackexchange.com/)上发布此信息。 – leigero