WordPress Custom post Templates

You can use a specific post template for single posts that you want to function differently. In a recent project i worked on, i didn’t want the posts in the news category to look or behave like the rest of the posts, i thought it would be better to have another template for the posts in the “news” category. I found a smart solution, you will need to put only the code below in your single.php file in your current theme folder:

$post = $wp_query->post;
if ( in_category('13') ) {
include(TEMPLATEPATH . '/single13.php');
} else {
include(TEMPLATEPATH . '/single1.php');

Here we are telling WordPress: If the post is in category ID number 13, display single13.php. If not in category ID number 13, display single1.php. Now you just create 2 new files “single13.php” & “single1.php”, and do whatever you want to do. From this, you can make as many single post page looks as you want, as long as they are styled by their category.

WordPress Single Post Templates- this post goes through a simple technique to have post templates like page templates. Here’s the code to add to your theme’s functions.php file. (be sure you paste this code between tags):

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

This technique solve the multiple categories issue (a post is included in more than one category) since it cycles through all the categories in the array and checks to see which one of them has an associated post template. When it finds one, it uses the post template file, but if it doesn’t, then it falls back on the default single.php template.


One Response to “WordPress Custom post Templates”

  1. controltheweb Says:

    So these are two different methods to achieve the same thing, except the second takes stock of multiple categories?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: