Adding a single post template based on parent category

We often have requirements where posts under a single category must be shown using a different template file in WordPress. THe code below allows you to search for a post’s parent or grandparent category and show the template based on the parent or grandparent category.

Add the following code to your functions.php to find the correct single post template.

//Gets post cat slug and looks for single-[cat slug].php and applies it
add_filter('single_template', create_function(
'$the_template',
'foreach( (array) get_the_category() as $cat ) {
if ( file_exists(TEMPLATEPATH . "/single-{$cat->slug}.php") )
return TEMPLATEPATH . "/single-{$cat->slug}.php";
else if($cat->category_parent)
{
$parent = get_category($cat->category_parent);
if ( file_exists(TEMPLATEPATH . "/single-{$parent->slug}.php") )
return TEMPLATEPATH . "/single-{$parent->slug}.php";
}
}
return $the_template;' )
);

Disclaimer: This code was found while searching the web. We have made modifications as per our requirements. All credits to the original author of the code

Leave a Reply

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