How to display number of posts in wordpress category including subcategories?

自作多情 提交于 2021-02-11 12:28:19

问题


While listing category, I want to show how many posts are there including subcategories. I tried this:

$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' ); ?>

The above works fine if category has no childs. But if I click on category which has subcategories, I see 0 posts found even if there are posts, but all of them are in subcategory (so 0 posts in parent category but some posts in subcategory)

Where did I go wrong and what should I change?


回答1:


Try using this function:

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;
}

this function will return total post counts from the specified category and its child categories (if any), just by passing the category id. i hope it works for you, thanks..



来源:https://stackoverflow.com/questions/36208115/how-to-display-number-of-posts-in-wordpress-category-including-subcategories

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!