Hierarchical WordPress templates

Another useful piece of code for you to put into your functions.php file. You probably already know that a file in your theme dir called category-1.php will be used for showing content for the category that has an id of 1. The filters below allow you to have hierarchical templates based on category id. For instance, all single posts belonging to category 1 will use single-cat-1.php. Also, all child categories of category 1 will use category-1.php.

// search for a template for the current post
// template is based on the current category id
// if no category template is found, keep searching parent categories
// filename structure: single-cat-0.php where 0 is the number of the category id 

function mytheme_single_template($template)
{
  foreach( (array) get_the_category() as $cat ) 
  {   
    // get template for current category
    $file = TEMPLATEPATH . '/single-cat-' . $cat->term_id . '.php';
    if (file_exists($file)) return $file;
    
    // search ancestor categories
    while ($cat->category_parent != 0)
    {
      $cat = get_category($cat->category_parent);
      $file = TEMPLATEPATH . '/single-cat-' . $cat->term_id . '.php';
      if (file_exists($file)) return $file;
    }
  }
  
  // return original template
  return $template;
}
add_filter('single_template', 'mytheme_single_template');

// search for a template for the current category
// template is based on the current category id
// if no category template is found, keep searching parent categories
// filename structure: category-0.php where 0 is the number of the category id 

function mytheme_category_template($template)
{ 
  $cat_id = get_query_var('cat');
  $cat = get_category($cat_id);
  
  $file = TEMPLATEPATH . '/category-' . $cat->term_id . '.php';
  if (file_exists($file)) return $file;
  
  while ($cat->category_parent != 0)
  {
    $cat = get_category($cat->category_parent);
    $file = TEMPLATEPATH . '/category-' . $cat->term_id . '.php';
    if (file_exists($file)) return $file;
  }
  
  return $template;
}
add_filter('category_template', 'mytheme_category_template');