Blog / WordPress/ How to Make WordPress Child Category Pages Use the Parent Category Template

How to Make WordPress Child Category Pages Use the Parent Category Template

WordPress子分类页面使用父分类页面模板

When developing a WordPress theme, it's often desirable for child category pages to use the same template as their parent category. This approach can significantly reduce repetitive development work.

This tutorial explains how to make WordPress child category pages automatically use their parent category's template.

Code Implementation

Add the following code to your theme's functions.php file:

// WordPress child category uses parent category template
add_filter('category_template', 'f_category_template');
function f_category_template($template) {
    $category = get_queried_object();
    // If the current category has a parent, traverse up to the top-level parent
    if ($category->parent != '0') {
        while ($category->parent != '0') {
            $category = get_category($category->parent);
        }
    }
    $templates = array();
    if ($category) {
        // Prioritize templates named by the parent category slug or ID
        $templates[] = "category-{$category->slug}.php";
        $templates[] = "category-{$category->term_id}.php";
    }
    // Fall back to the default category.php
    $templates[] = 'category.php';
    return locate_template($templates);
}

How It Works

This code uses the WordPress category_template filter to modify the template lookup logic for category pages. The process is:

  1. Get the currently queried category object.
  2. Check if it has a parent (parent != '0').
  3. If yes, loop upward until the top-level parent category is found.
  4. Then, the system will look for these template files in order:
    • category-{top-parent-slug}.php
    • category-{top-parent-id}.php
  5. If none exist, it falls back to the default category.php.

Important Notes

  • This method only works for WordPress's built-in "Categories." For custom taxonomies, use the corresponding filter (e.g., taxonomy_template).
  • Ensure your theme directory contains the necessary template files (like category.php); otherwise, the page won't display correctly.
  • After modifying the code, clear your site cache to ensure the changes take effect.

Post a Comment

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