2015-10-19 71 views
-1

如何获得定制分类术语内的帖子数量? (包括附属于子期限的职位)。获取定制分类的术语内部没有帖子

例如我有:

  • 术语(2个)

  • 柴尔德术语(2个)

  • --child子项(1柱)

现在我是,像这样:

$categories = get_terms($taxonomy,$args); 
foreach ($categories as $categ) { 
    print $categ->name.'/'.$categ->count; 
} 

但是对于“term”我只有2个帖子,当我真的需要显示5(2个来自“term”和3个来自它的孩子)。

感谢

+0

你可能会有更多的运气在[Wordpress Exchange](http://wordpress.stackexchange.com/)上发布此信息。 – leigero

回答

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

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); 
} 
+0

感谢您的答复 - 我会在几个地方尝试。一个问题:当你有很多条件时,递归函数是否会增加加载时间或内存消耗? – Crerem

+0

是的,它只是一点点,但不如'get_terms'的返回缓存 - 但请注意,它不是一个持久性缓存,所以它会阻止查询在页面加载时执行两次 - 所以当你查询你的模板上的孩子,它将来自缓存,因为它已经在递归函数中执行过了。 – vard

+0

这很整洁......但效率很低。 – rnevius

相关问题