Blog / WordPress/ How to Get the Post Count for a Custom Category in WordPress

How to Get the Post Count for a Custom Category in WordPress

WordPress获取自定义分类文章数量总数

Many WordPress users need to display the total number of posts within a specific category, including custom taxonomies. This guide explains how to accurately retrieve these counts.

Understanding wp_count_posts()

The wp_count_posts() function is commonly found when searching for post count solutions. However, it's crucial to understand its purpose and limitations.

Function Signature:

wp_count_posts( string $type = 'post', string $perm = '' )

Parameter Explanation:

  • $type (string, optional): The post type name (e.g., 'post', 'page', or a custom post type). Default is 'post'.
  • $perm (string, optional): Checks 'readable' permissions for private posts. Accepts 'readable' or an empty string (default).

Example: Count Posts for a Custom Post Type

$count_posts = wp_count_posts('site'); // 'site' is a custom post type name
if ( $count_posts ) {
    $published_posts = $count_posts->publish;
}

Important Note: wp_count_posts() returns counts for an entire post type, not for specific categories or taxonomy terms.

How to Get Post Count for a Specific Category

To get the number of posts assigned to a specific category or term within a custom taxonomy, you must work with the term object directly.

The core method involves retrieving the term and accessing its built-in count property.

Method 1: Using get_term() with Term ID

Use this when you know the term ID and taxonomy name.

// Example: Taxonomy 'website_nav', Term ID 5
$term = get_term(5, 'website_nav');
if ($term && !is_wp_error($term)) {
    $post_count = $term->count;
    echo 'Post count for term "' . $term->name . '": ' . $post_count;
}

Method 2: Using get_term_by() with Slug

Use this when you know the term's slug (and taxonomy name).

$term = get_term_by('slug', 'your-category-slug', 'website_nav');
if ($term && !is_wp_error($term)) {
    $post_count = $term->count;
    // Use $post_count as needed
}

These methods work for both default categories (taxonomy: 'category') and custom taxonomies. The count property is automatically maintained by WordPress and reflects the number of published posts assigned to that term.

By using get_term() or get_term_by(), you can accurately display the post count for any category or custom taxonomy term on your site.

Post a Comment

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