Single Posts by Category

Several of my themes use a handy plugin called Single Post Templates which allows you to choose a template for any post just like you can for a page.  It’s a great feature that I think WordPress should roll into the core.  One thing I’ve noticed is that many people use the post templates on a category basis.  On my site, I have post templates for blog entries, theme information pages and then general posts.  Since the templates are based on categories I use the following code to make the post templates work instead of the plugin.  Here’s how it works.

If your theme already has a single.php, rename it single-original.php and create a new file called single.php.  Now into this empty file, paste the following code:


<?php $post = $wp_query->post;

  if (in_category('9')) {
      include(TEMPLATEPATH.'/single-9.php');
  } elseif (in_category('4')) {
      include(TEMPLATEPATH.'/single-4.php');
  } else {
      include(TEMPLATEPATH.'/single-original.php');
  }
?>
<?php get_header(); ?>
<?php get_footer(); ?>

Here’s how it works. The code checks to see if what category you’re in (in this example the category id is 9). If the post is in that category it will display the single-9.php template for that post. After checking to see if it is in category 9, then it checks to see if the post is in category 4. If it is then it displays single-4.php. If not then it displays our original post template single-original.php.

The big advantage that the plugin provides is the ability to choose a template on a per post basis regardless of category. However using this snippet takes care of things automatically and that can be quite useful too.

Leave a comment