How to Get the Number of Posts in a Specific WordPress Category

In the WordPress database, each category already stores the number of posts assigned to it. Even so, WordPress does not provide a dedicated function for retrieving that number directly. When developing a WordPress theme or application, we occasionally need this data. Below are two ways to get the number of posts in a category, and you can choose whichever one you prefer.

Get it directly with an SQL query

This method gets the value directly through an SQL query. The data returned is simply the number of posts in the category. Compared with the method below, it is a little more straightforward.

function wizhi_get_category_count($input = '') {
    global $wpdb;

    if($input == '') {
        $category = get_the_category();
        return $category[0]->category_count;
    }
    elseif(is_numeric($input)) {
        $SQL = "SELECT $wpdb->term_taxonomy.count FROM $wpdb->terms, $wpdb->term_taxonomy WHERE $wpdb->terms.term_id=$wpdb->term_taxonomy.term_id AND $wpdb->term_taxonomy.term_id=$input";
        return $wpdb->get_var($SQL);
    }
    else {
        $SQL = "SELECT $wpdb->term_taxonomy.count FROM $wpdb->terms, $wpdb->term_taxonomy WHERE $wpdb->terms.term_id=$wpdb->term_taxonomy.term_id AND $wpdb->terms.slug='$input'";
        return $wpdb->get_var($SQL);
    }
}

Get it with a new WP_Query

This method uses WordPress’s standard custom query system. The returned data is a set of post objects for all posts in the category, which includes a lot of unnecessary information. In terms of performance, it is a little worse than the method above, but the code is more in the WordPress style and will not create compatibility issues if the WordPress data structure changes.

if ( ! function_exists( 'wizhi_get_category_count' ) ) :
function wizhi_get_category_count( $cat_id ) {
    $q = new WP_Query( array(
        'nopaging' => true,
        'tax_query' => array(
            array(
                'taxonomy' => 'category',
                'field' => 'id',
                'terms' => $cat_id,
                'include_children' => true,
            ),
        ),
        'fields' => 'ids',
    ) );
    return $q->post_count;
}
endif;

Note: Both methods return the same result, so using either one is enough.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *