Alessandro Melandri

WebSphere Commerce Specialist, project manager, wannabe photographer

Single Post Template Based on Category #2

In my previous post I talked about a Lorelle blog post on creating single post templates for different categories.

After using the code snippets “as is” I tryed to build a more flexible solution so I’ve come up with this little function:

1
2
3
4
5
6
7
8
9
10
function getSingleTemplate(){
 
  $category = get_the_category();
  $templateName = TEMPLATEPATH . '/single_' . $category[0]->category_nicename .'.php';
 
  if (!file_exists($templateName)){
    $templateName = TEMPLATEPATH . '/single_default.php';
  }
  return $templateName;
}

This function must be called inside the single.php template: it gets the first post’s category, searches for a template named like singlepost_first_category_slug.php and returns its path; if the file doesn’t exists it will return the single_default.php_ template path.