9/9/2018 - 8:58 PM

Create custom WordPress Templates that load based on category

There are just two steps to this process: Create a function to activate custom single post templates and creating the actual template itself. Let’s tackle the first one first. What you need to do is write a function – to be placed in functions.php of your theme or child-theme – that grabs the category info for the post in question and checks if there is a custom single post template that matches that particular category. That function looks something like below.

This function, actually a filter, finds the category slug(s) for the post and checks if there is a template file called single-[slug].php in the theme. If there is, that tempalte is used in place of single.php. So for example if you have a category called Portfolio with the slug “portfolio” you can create a new file called single-portfolio.php that will then become the custom single post template for posts assigned to this category.

add_filter('single_post_template', create_function(
	'foreach( (array) get_the_category() as $cat ) {
		if ( file_exists(TEMPLATEPATH . "/single-{$cat->slug}.php") )
		return TEMPLATEPATH . "/single-{$cat->slug}.php"; }
	return $the_template;' )