Counting number of posts in a category and its sub categories and displaying result using shortcode

The shortcode

// Add Shortcode to show posts count inside a category
function category_post_count( $atts ) {

    $atts = shortcode_atts( array(
        'category' => null
    ), $atts );

    // get the category by slug.
    $term = get_term_by( 'slug', $atts['category'], 'category');

    return ( isset( $term->count ) ) ? $term->count : 0;
}
add_shortcode( 'category_post_count', 'category_post_count' );

Usage

[category_post_count category="category_slug_or_name"]

If you want to get the count by name, not slug change this

$term = get_term_by( 'slug', $atts['category'], 'category');

to this:

$term = get_term_by( 'name', $atts['category'], 'category');

Leave a Comment