WordPress: Custom Single Templates by Category


Back in 2008 there was a blog entry on how to do this. Throughout the comments of the article were about 15 different versions of how to accomplish getting different single.php templates for different categories. I went through them and combined them into what I feel is the best solution that keeps in tune with other WordPress naming conventions.

First add the function below to your theme functions.php

add_filter('single_template', 'check_for_category_single_template');
function check_for_category_single_template( $t )
{
  foreach( (array) get_the_category() as $cat ) 
  { 
    if ( file_exists(get_stylesheet_directory() . "/single-category-{$cat->slug}.php") ) return get_stylesheet_directory() . "/single-category-{$cat->slug}.php"; 
    if($cat->parent)
    {
      $cat = get_the_category_by_ID( $cat->parent );
      if ( file_exists(get_stylesheet_directory() . "/single-category-{$cat->slug}.php") ) return get_stylesheet_directory() . "/single-category-{$cat->slug}.php";
    }
  } 
  return $t;
}

Second you need to duplicate your current single.php file and rename it to the following naming convention.

If the category slug is 'photos' then you use single-category-photos.php

If the category slug is 'hamburgers' then you use single-category-hamburgers.php

You’re probably asking why the annoyingly long template name. Well there will be a time (or a plugin you install) that will have a custom post type as ‘photos’ or ‘hamburger’ and this will allow those custom post types to have the built-in ‘single-photos.php’ name. That and it’s super easy to understand.

Enjoy.