Wordpress Snippets

Force Sub Categories To Use Parent Category Templates

When a viewer clicks on a link to one of the Categories on your WordPress site, he or she is taken to a page listing the Posts in that particular Category in chronological order. WordPress uses `category.php` template as a default layout to display all category listing pages. But you also have option to define your own custom category templates too. Defining template for a particular category is easy. All you have to do is create a file named as `category-{category-slug}.php`. So if your category slug is “news” then your category template name will be `category-news.php`. In a recent project I was required to define category template for a parent category, and then had to make sure that all the child categories under that parent must inherit the same template used by the parent category.

To solve my little problem I created this following function which uses category_template WordPress filter to assign parent category template to all child categories and sub-categories. First I got the current category by using the function get_queried_object() and then checked if the current category has a parent category, if it does then it will search for the parent category by using the get_category() function, if this isn’t empty then we add the extra templates to the array using the parent slug and parent ID.

Simply pasting this WordPress code snippet in your theme’s functions.php file will force WordPress to use parent category templates on all sub-categories.

// force sub categories to use parent category templates
function wcs_force_use_parent_category_template() {

    $category = get_queried_object();
    $templates = array();

    // Add default category template files
    $templates[] = "category-{$category->slug}.php";
    $templates[] = "category-{$category->term_id}.php";

    if ( $category->category_parent != 0 ) {
        $parent = get_category( $category->category_parent );

        if ( !empty($parent) ) {
            $templates[] = "category-{$parent->slug}.php";
            $templates[] = "category-{$parent->term_id}.php";
        }
    }

    $templates[] = 'category.php';
    return locate_template( $templates );
}
add_filter( 'category_template', 'wcs_force_use_parent_category_template' );

Hire Us. Or just say Hi!
Need a job? Apply to get one.