Snippet: Configure Child Categories to use their Parent Category Template

WordPress categories follow a predefined template hierarchy. In most cases, we use “category-$slug.php” to override the template for an individual category to give it a entirely different look and functionality (“category-projects.php” for a “Project” category). If you have subcategories (Design, Development etc) of “Project” they also follow the WordPress template hierarchy and you have to create “category-design.php” and “category-development.php” to give them the similar look as of Projects category. This snippet allow you to configure some or all child categories to use their parent’s category template. In the scenario we just mentioned above, Design and Development categories will also land at “category-projects.php” instead of their own “category-$slug.php” template.

Snippet

add_action('template_redirect', 'wpds_parent_category_template');
function wpds_parent_category_template()
{
    if (!is_category())
        return true; 

    // get current category object
    $cat = get_category(get_query_var('cat'));
    
    while ($cat && !is_wp_error($cat)) {
        $template = TEMPLATEPATH . "/category-{$cat->slug}.php";
        // load if template file exsits.
        if (file_exists($template)) {
            load_template($template);
            exit;
        }

        $cat = $cat->parent ? get_category($cat->parent) : false;
    }
}

Override template for Individual categories

Only the “Design” subcategory of “Projects” category will use “category-projects.php”.

add_action('template_redirect', 'wpds_parent_category_template');
function wpds_parent_category_template()
{
    if (!is_category())
        return true; 

    // Override template for individual "design" category whose parent is "projects" category 
    if (is_category('design') && cat_is_ancestor_of(get_cat_id('projects'), get_query_var('cat'))) {
        $cat = $cat->parent ? get_category($cat->parent) : false;
        $template = TEMPLATEPATH . "/category-{$cat->slug}.php";
        // load if template file exsits.
        if (file_exists($template)) {
            load_template($template);
            exit;
        }
    }
}

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>