How to Count All Posts in Category in WordPress

Md Riyazuddin Verified
You are looking for a way to count all posts in a particular category and show it in WordPress. There is probably a plugin to do this. We have created a short code snippet you can use in WordPress to count all posts in a specific category.
Simply add the code to your theme's functions.php:

function count_category_post( $category )  {

    if( is_string( $category ) ) :
        $category_Id = get_cat_ID( $category );
    elseif( is_numeric( $category ) ) :
        $category_Id = $category;
    endif;

    $cat = get_category( $category_Id );

    return ! empty( $cat->count ) ? $cat->count : 0;

}

You can use this code for the post count of a particular category on any page of your website by either category ID or name:

echo  count_category_post(1);
echo  count_category_post('category_name');


Tags

NA

Comments

Leave a Comment