Use Different Single Post Templates for Different Categories in WordPress

Chris — February 24, 2009

I recently had to figure out how to use a separate post template for a specific category like you can with pages in wordpress. I found a solution at nathanrice.net.

Just add the following code to you functions.php file:

<?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;' )); ?>

Then all you have to do is create a new single post template and name it “single-X.php” where “X” is the category ID of your choice.

If you have multiple categories assigned to a single post and they both have special templates you’ll run in to problems. This code will select the template of the category with the largest number.

No Comments »

RSS feed for comments on this post. TrackBack URL

Leave a comment