Custom Single Template per Category

September 16th, 2015 by
Add this filter to your 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(TEMPLATEPATH . "/single-category-{$cat->slug}.php") ) return TEMPLATEPATH . "/single-category-{$cat->slug}.php"; 
    if($cat->parent)
    {
      $cat = get_the_category_by_ID( $cat->parent );
      if ( file_exists(TEMPLATEPATH . "/single-category-{$cat->slug}.php") ) return TEMPLATEPATH . "/single-category-{$cat->slug}.php";
    }
  } 
  return $t;
}
Then name your template single-category-{category-slug}.php with no curly braces, example if your category name is Shaka the slug would be shaka, therefor the file name will be single-category-shaka.php

Post a Comment

You must be logged in to post a comment.

Cached at: 2024-11-03 01:14:35pm