Blog / WordPress/ How to Get All Subcategories of the Current Category in WordPress

How to Get All Subcategories of the Current Category in WordPress

WordPress获取当前分类下的所有子分类

How to Get All Subcategories of the Current Category in WordPress

In WordPress development, retrieving all subcategories under a parent category is a common requirement. This article explains how to implement this functionality through code.

Core Concept

The main approach uses the built-in WordPress function wp_list_categories(). A helper function obtains the root (top-level parent) category ID of the current category, which is then passed to the child_of parameter of wp_list_categories() to list all direct subcategories under that root category.

Step 1: Add the Helper Function

First, add the following function to your current theme's functions.php file. This function retrieves the root category ID for any given category.

// Get the root (top-level parent) category ID for a specified category
function get_category_root_id($cat) {
    $this_category = get_category($cat); // Get the category object
    // Loop upwards until a category with no parent is found (the root)
    while($this_category->category_parent) {
        $this_category = get_category($this_category->category_parent);
    }
    return $this_category->term_id; // Return the root category ID
}

Explanation: This function accepts a category ID or object as a parameter. It iteratively traces parent categories upwards until it finds the top-level category and returns its ID.

Step 2: Call the Function in Your Template

Insert the following code in the template file (e.g., category.php, single.php, or a page template) where you want to display the subcategory list. You typically need to get the current category ID first.

<?php
// Get the current category ID. On category archive or single post pages:
$current_cat_id = get_queried_object_id();
// Call wp_list_categories to list direct subcategories under the root category
wp_list_categories(array(
    'child_of'           => get_category_root_id($current_cat_id), // Key parameter: root category ID
    'title_li'           => '', // Remove the default list title (e.g., 'Categories')
    'orderby'            => 'name', // Sort by name
    'show_count'         => 1, // Show post count per category
    'use_desc_for_title' => 1, // Use category description as link title attribute
    'hierarchical'       => 1, // Maintain hierarchical structure (affects CSS classes)
    'show_option_none'   => __('<span style="padding:0 20px;">No subcategories.</span>'), // Message if none
    'depth'              => 1, // Display only one level (direct children)
    'taxonomy'           => 'category', // Taxonomy, default is 'category'
));
?>

Key Parameters Explained

  • child_of: The crucial parameter. It specifies a category ID, and the function lists all its subcategories. We dynamically pass the root category ID using get_category_root_id().
  • depth: Set to 1 to show only direct subcategories. Use 0 to display all descendant levels.
  • show_count: Controls whether to show the number of posts in each category (replaces the deprecated optioncount).
  • title_li: Set to an empty string to remove the default list title for a cleaner output.

Usage and Considerations

  1. Identifying the Current Category: On category archive pages, use get_queried_object_id(). On single post pages, use get_the_category() to get the post's first category.
  2. Styling: wp_list_categories() outputs HTML with specific CSS classes (e.g., .cat-item). You can customize the appearance with your own CSS.
  3. Performance: For sites with deep category hierarchies or many categories, the helper function may cause multiple database queries. Consider caching the result for high-performance sites.

Following these two steps allows you to dynamically display a list of all subcategories under the root category of the current section in your WordPress site.

Post a Comment

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