如何在自定义分类法的术语中获得帖子的数量? (包括附属于儿童任期的职位)。
例如我有:
任期(2个职位)
-child term(2个帖子)
- 儿童用语(1个帖子)
现在,我这样做:
$categories = get_terms($taxonomy,$args);
foreach ($categories as $categ) {
print $categ->name.' / '.$categ->count;
}
但对于"术语"当我真的需要显示5个时,我只得到2个帖子(2个来自"术语"以及3个来自它的孩子)。
由于
答案 0 :(得分:1)
有一种更简单的方法:执行标准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。
答案 1 :(得分:0)
这是我遇到过几次的事情,我改变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);
}