X

How to Use Category Parent Template in WordPress

Snippets by IsItWP

Are you looking for a way to use category parent template without creating templates for subcategories? While there’s probably a plugin for this, we have created a quick code snippet that allows you to use category parent template in WordPress.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:


function load_cat_parent_template()
{
    global $wp_query;
    if (!$wp_query->is_category)
        return true; // saves a bit of nesting
    // get current category object
    $cat = $wp_query->get_queried_object();
    // trace back the parent hierarchy and locate a template
    while ($cat && !is_wp_error($cat)) {
        $template = TEMPLATEPATH . "/category-{$cat->slug}.php";
        if (file_exists($template)) {
            load_template($template);
            exit;
        }
        $cat = $cat->parent ? get_category($cat->parent) : false;
    }
}
add_action('template_redirect', 'load_cat_parent_template');

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 10 best WordPress plugins for web developers and how to start a blog from scratch.

Comments   Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!