Blog / WordPress/ How to Get Total Post Count for a Category and Its Subcategories in WordPress

How to Get Total Post Count for a Category and Its Subcategories in WordPress

WordPress 获取指定分类及其子分类文章总数量的完整方法

In WordPress development, you may need to count the total number of posts within a specific category, including all its subcategories. This article provides an efficient, standard PHP function to achieve this, along with detailed usage instructions.

Core Function

Add the following PHP code to your current theme's functions.php file. This function accepts a category ID and returns the total post count for that category and all its subcategories.

/**
 * Get total post count for a category and all its subcategories.
 *
 * @param int $category_id The category ID to count.
 * @return int Total post count.
 */
function get_category_post_count_with_children($category_id) {
    // Validate input: ensure positive integer.
    if (!is_numeric($category_id) || $category_id <= 0) {
        return 0;
    }

    // Get main category post count.
    $main_category = get_category($category_id);
    if (is_wp_error($main_category) || !$main_category) {
        return 0;
    }
    $count = (int) $main_category->count;

    // Get all child category IDs.
    $child_categories = get_terms(array(
        'taxonomy' => 'category',
        'child_of' => $category_id,
        'hide_empty' => false,
        'fields' => 'ids'
    ));

    // Return main count if no children or error.
    if (is_wp_error($child_categories) || empty($child_categories)) {
        return $count;
    }

    // Sum counts from all child categories.
    foreach ($child_categories as $child_cat_id) {
        $child_category = get_category($child_cat_id);
        if (!is_wp_error($child_category) && $child_category) {
            $count += (int) $child_category->count;
        }
    }

    return $count;
}

Function Explanation & Optimizations

This function includes several improvements:

  • Robust error handling: Checks return values of get_category and get_terms to prevent PHP errors.
  • Performance optimization: Uses 'fields' => 'ids' in get_terms to reduce database load.
  • Clear documentation: Comments explain purpose, parameters, and return value.
  • Input validation: Ensures the category ID is a valid positive integer.

Usage Examples

Call the function in your theme template files (e.g., category.php, archive.php, sidebar.php).

Example 1: Direct Output

<?php
$total_posts = get_category_post_count_with_children(5);
echo 'This category and its subcategories contain ' . esc_html($total_posts) . ' posts.';
?>

Example 2: Within a Loop or Conditional

<?php
$current_cat_id = get_queried_object_id();
$post_count = get_category_post_count_with_children($current_cat_id);

if ($post_count > 0) {
    echo '<p>Found ' . $post_count . ' related posts.</p>';
}
?>

Important Considerations

  • Caching: For high‑traffic sites or frequent calls, cache results using WordPress Transients API or Object Cache.
  • Multisite: The function counts posts only for the current site in a Multisite network.
  • Custom Post Types: It counts only default 'post' type. For custom post types, modify the get_terms query or use WP_Term_Query.

This method provides an accurate and efficient way to retrieve the total post count for any WordPress category and its subcategories, suitable for theme development.

Post a Comment

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