WordPress: 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 “has is” I tryed to build a more flexible solution so I’ve come up with this little function:

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 “single_post_first_category_slug.php” and returns its path; if the file doesn’t exists it will return the single_default.php template path.

My single.php template:

<?php
$post = $wp_query->post;
include( getSingleTemplate() );
?>

One Response

  1. [...] is the original: WordPress: single post template based on category #2 | Alessandro … No Comments Read [...]

Leave a Reply