SJL Web Design

WordPress Category Templates

We have recently been working on a WordPress website that needed two templates for different categories, one with a serious news article presence and another with a more laid back blog look and feel. We wanted this to be automatic so when the client placed a post into a category it would automatically assign it with the appropriate template. After reading around and trying a couple of different things we found that the solution was pretty straightforward.

The ideal way was to redirect the default single.php to the correct template based on the category ID. To do this we first backed up our single.php file by saving it as single1.php we then saved it two more times; single-news.php and single-blog.php. We then altered these two files according to the client’s request.

We then replaced all of the existing code in single.php with the following piece of PHP


<?php
$post = $wp_query->post;
if ( in_category('39') ) {
include(TEMPLATEPATH . '/single-news.php');
} else {
include(TEMPLATEPATH . '/single-blog.php');
}
?>

This will take any blog posts from category 39 and load them using the single-news.php template. Other blog posts from different categories will load the default single-blog.php template.

Tip: You can find the category ID by going to Posts > Categories in the WordPress admin area and clicking edit under to the desired category. Then look out for a string similar to this in the URL tag_ID=39, that’s the ID for that category.

More templates for different categories?

If you need more templates for different categories you can still use the above code just add the elseif statement:


<?php
$post = $wp_query->post;
if ( in_category('39') ) {
include(TEMPLATEPATH . '/single-news.php');
} elseif(in_category('50')) {
include(TEMPLATEPATH . '/single-other.php');
}
else {
include(TEMPLATEPATH . '/single-blog.php');
}
?>

Leave a Reply