2016-03-24 262 views
0

虽然列出类别,我想显示有多少职位,包括子类别。我试过这个:如何显示wordpress类别中包括子类别的帖子数量?

$cat_parent_ID = isset($cat_id->category_parent) ? $cat_id->category_parent : ''; 

      if ($cat_parent_ID == 0) { 

       $tag = $cat_id; 

      } else { 

       $tag = $cat_parent_ID; 

      } 
$q = new WP_Query(array(
        'nopaging' => true, 
        'tax_query' => array(
         array(
          'taxonomy' => 'category', 
          'field' => 'id', 
          'terms' => $tag, 
          'include_children' => true, 
         ), 
        ), 
        'fields' => 'ids', 
       )); 
       $allPosts = $q->post_count; 

       echo $allPosts; 
      ?> 

      <?php _e('posts found', 'agrg'); ?> 

上面的工作正常,如果类别没有孩子。但是,如果我点击具有子类别的类别,即使有帖子,我也会看到0 posts found,但是它们都在子类别中(所以在父类别中有0个帖子,但在子类别中有一些帖子)

我哪里出错了?我应该改变吗?

回答

1

尝试使用此功能:

function wp_get_cat_postcount($id) { 
    $cat = get_category($id); 
    $count = (int) $cat->count; 
    $taxonomy = 'category'; 
    $args = array(
     'child_of' => $id, 
    ); 
    $tax_terms = get_terms($taxonomy,$args); 
    foreach ($tax_terms as $tax_term) { 
     $count +=$tax_term->count; 
    } 

    return $count; 
} 

此功能会从指定的类别及其子类别(如果有的话),只是通过将类别ID返回总职位数。 我希望它适合你,谢谢..

+0

完美的作品,谢谢! –

+0

如果一篇文章被分配到多个子类别,它会被多次计数,所以您使用此功能会得到错误的结果 – marvin

相关问题