2016-03-24 13 views
0

カテゴリの一覧表示中、サブカテゴリを含む投稿数が表示されます。私はこれを試しました:サブカテゴリーを含むワードプレスカテゴリの投稿数を表示するには?

$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件、サブカテゴリの投稿は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