subscribe:
facebook
twitter
tumblr
email
rss

WordPress: Unique display for post in a category

If you have ever wondered how to make your single posts from a certain category in WordPress have their own template, then read on. This is especially useful when using WordPress as a CMS with plugins that provide custom write panels, such as Flutter or More Fields.

The solution is an easy one, and closely related to my Category Template by Slug solution, but this time the credit will have to go to Nathan Rice and Austin Matzko.

Here is the code:

add_filter('single_template', 'my_post_by_name');
 
function my_post_by_name($template) {
  foreach(get_the_category() as $cat) {
    if (file_exists(TEMPLATEPATH."/single-".$cat->slug.".php")) :
      return TEMPLATEPATH."/single-".$cat->slug.".php";
    endif;
  } return $template;
}

Simply past this code in your functions.php file in your theme directory.

Now, when you have a category called mycategory and you create a file called single-mycategory.php in the template directory WordPress will use this file to display the single post.

Note: If a post is assigned to multiple categories the wrong category could be selected. If you need a more versatile solution you can check out Nathan’s Single Post Template plugin.

Date: July 10, 2009
Author: Diaan Mynhardt
Tags: ,

Comments are closed.