Select Custom Post Template Based on Category

I rely on custom post templates on one of my sites.  Recently I ran into an issue when I upgraded to WordPress 3.01.Wordpress 3.01 I used the plugin Category Templates to assign my posts a specific custom post template.  After the upgrade to 3.01 The Category Templates plugin partially broke.  I could still go into an individual post and select which Custom Post Template to use but all of my posts lost the initial custom post template they were assigned to.  The Custom Post Template plugin also has a bulk assignment utility but that didn’t work after the upgrade.  I was stumped for a couple of days on how to easily resolve the problem.  Manually going into 13,000 posts wasn’t an option!

In my research I stumbled across a posting on the WordPress forums.  Ronald73 posted a coding solution that accomplished exactly what I needed.  Here is his solution:

  • Add the following code to the theme’s functions.php:
  • add_filter(‘single_template’, create_function(‘$t’, ‘foreach( (array) get_the_category() as $cat ) { if ( file_exists(TEMPLATEPATH . “/single-{$cat->term_id}.php”) ) return TEMPLATEPATH . “/single-{$cat->term_id}.php”; } return $t;’ ));
  • Create a file named single-xx.php (where xx is the ID of the category)  Save it in your themes folder.
  • All posts in this category will now use the single-xx.php instead of single.php

My testing shows this solution work brilliantly!  Also, now I have one less plugin to run on my installation.

1 comment for “Select Custom Post Template Based on Category

  1. January 30, 2011 at 12:35 pm

    Hey, thanks for this testing 🙂

Leave a Reply to spargelrezepte Cancel reply

Your email address will not be published. Required fields are marked *


Subscribe without commenting