How to Set Up Custom Wordpress Category Templates in Four Easy Steps
In a recent project, I needed to distinguish blog-style posts from longer, stand-alone articles in WordPress. The blog posts needed to look one way, and the articles, another. One type needed to look like a pretty typical blog post, but the other needed to look more like a New York Times story page. My basic goal was to categorize stories as either "posts" or "articles," and let WordPress apply the proper template for me. Seemed like it should be easy… until I tried to figure out how to make it work.
I found the explanations in the WordPress codex confusing and unhelpful. I searched around for some other solutions and didn’t find much to help me sort this out. Most articles or posts on the matter were knee-deep in code and long scripts. Finally, I found this post by Lorelle on "Creating Multiple Single Posts for Different Categories" which was tremendously useful. However, I still found the explanation a bit fuzzy. I sorted it out, but think a clearer take on this might help other similarly baffled WordPress users:
Step 1: Design two (or more) custom templates. A good way to start is to copy the "single.php" file from the default templete and modify it to suit your needs. In my case, I set up one template called "blogpost.php" and another called "article.php." I prefer to have descriptive template file names. Need more help? I’ve found Ben Gillbanks’ short tutorial on creating custom templates useful. Ok, so once you’ve got your custom templates worked up, copy them into your theme directory.
Step 2: Back-up your single.php file. Since the next step will destroy your single.php file as it currently exists, take a few seconds and make a copy of your working file, just in case something goes wrong. You can always replace your modified single.php file with the original to change everything back to the way it was before you started tinkering. Better safe than sorry, right?
Step 2: Turn the "single.php" into doorway to your custom templates. In a normal WordPress theme, the "single.php" file, also known as the "Single Post" template, takes a post and styles it with this basic template. But if you want to use multiple post templates, you can use this file to help WordPress understand which one to use. The WordPress engine looks at the single.php file to style your post’s content, but since it is a PHP file, you can use it to redirect it to your custom templates.
So what we’re going to do is replace the single.php file with some very short code that tells WordPress to check the category of a post and then load the appropriate template. You use the categoryID number from the Manage | Categories tab to identify the correct category. Here’s how the code would look:
<?php
$post = $wp_query->post;
if ( in_category(’5′) ) {
include(TEMPLATEPATH . ‘/article.php’);} else {
include(TEMPLATEPATH . ‘/blogpost.php’);
}
?>
So let’s break this down. the first two lines set up a query. The second line tells WordPress that if a post matches category 5 (which happens to be the ID for my "article" category… your number would vary, obviously), load the template "article.php". The next lines say, basically, "ok, so if this isn’t an article, it’s a blog post, so go ahead and load "blogpost.php".
But what if you have more than two category-based templates? No problem. Your new best friend is a little conditional tag called “elseif.” Here’s how that would work:
<?php
$post = $wp_query->post;
if ( in_category(’5′) ) {
include(TEMPLATEPATH . ‘/article.php’);} elseif ( in_category(’6′) ) {
include(TEMPLATEPATH . ‘/column.php’);} else {
include(TEMPLATEPATH . ‘/blogpost.php’);
}
?>
So this three-way query tells WordPress, "if a post is category 5 (an article), load the article.php template, if it’s not category 5, then check to see if it is category 6 (a column) and load the column.php template if it matches that, otherwise, it must be a post, so load the blogpost.php template." You can set up as many “elseif” statesments as you need to match the number of custom post templates you want to use.
Go ahead and save your single.php file. That short snippet of code is all you need. You’re almost done.
4. Give it a test. If you did everything right, the single.php should act like a traffic cop and direct posts to the correct template, depending on their category. Test posts by category and see how they display. If the templates seem broken or no post shows up, you may be missing a bracket or semicolon someplace in your single.php file. Go back and double check it. Conditional statements (if, else, and elseif) can be a bit confusing, so it can help to check the syntax here. You might also need to make sure your custom templates don’t have any odd code that might mess up the display.
Hope this helps. Drop me a line if you have questions or comments…








October 9th, 2007 | 7:44 pm
Another explanation that might be clearer than mine, and a lot simpler, is in Using WordPress Categories To Style Posts, a much easier method than both of ours.
December 14th, 2007 | 6:09 pm
Dude! Thanks alot. I never got that the code should be replaced in single.php from the explanation given on the codex. Thanks for making this clear.
December 14th, 2007 | 6:10 pm
Dude! Thanks alot. I never got that the code should be replaced in single.php from the explanation given on the codex. Thanks for making this clear.
December 30th, 2007 | 6:52 am
Thanks for making this clear
December 30th, 2007 | 6:53 am
Thanks
July 19th, 2008 | 8:25 am
Hi – great info, very nicely explained. One further question. What if you have several categories for which you want to use specific templates (as above) but then want all other categories (which might be created on the fly) to have the standard look that single.php would have provided before it was changed? Not sure if that’s doable – but thought I’d ask.
Thanks!
July 19th, 2008 | 8:32 am
Sorry, figured it out. Just one of those “duh” moments!
August 5th, 2008 | 1:49 pm
Works like a charm! Thank you so much for this!
August 5th, 2008 | 2:03 pm
That’s pretty cool, I’m going to use this for sure.
Great stuff. Thanks a lot. I’ll let others know (and thanks to Selene M. Bowlby who alerted me to this on Twitter).
August 27th, 2008 | 7:00 am
[...] How to Resource Link… Creating Your Own Page Templates [...]
September 10th, 2008 | 8:10 am
Another slightly less complex alternative is to use the Idealien Category Enhancements plugin. It allows you to select templates through the admin consoles’ manage > categories window. Think of it as all the same customizability of page templates for either category.php or single.php without having to go and modify the php each time you add a new category or template.
September 21st, 2008 | 4:11 am
Hi,
I need some help, if possible. I have a blog that covers several different topics: Travel, Sports, etc…
I only want the header image to change for the category and the post.
For example, the homepage will have a header image when a visitor arrives.
If they click on the “Travel” category, the category page will show a header image of an airplane.
In the Travel category, I have a subcategory about Hawaii with posts. If someone clicks on a post in the Hawaii subcategory, the header image will show a picture of Hawaii.
I think I need to somehow customize the “archives.php” in my template but not sure how to do it.
I just want to control the header image of the categories and subcategories, the rest of the template should remain the same.
Is there a way to implement this using the information above?
Thanks in advance for your help
October 1st, 2008 | 11:09 pm
Thanks for the tutorial Matt. To get this to work for me (in WP 2.6.2) I had to alter my template files (copies of single.php) thus:
Replace the following:
With:
where ‘cat=3′ is the id of your category, and ‘posts_per_page=-1′ are the number of posts to display, in this case all.
Without the above I couldn’t get the template to display posts; the appropriate template for each category would load fine, but no posts would be displayed.
I am definitely no expert in PHP, so it is quite likely this can be refined/improved.
October 20th, 2008 | 4:40 am
i’m getting lost on step 2….
oops.. i meant – thanks fella. Big help! :)
October 20th, 2008 | 3:56 pm
Hey,
I am, John
Nice site, verry informative
check my site:
http://ARcA8NEZ.spaces.live.com/
October 25th, 2008 | 5:29 pm
This is just one hell of a great post :D
BUT.. I would like to ask for some help, becaouse this actually does not work for me. Me template is using single.php for blogposts as normalt themes do, and I do not quite understand why this solution you provide us with over does’nt work for me.
I just tried this as a test, so I created to files called “hei.php” and “hallo.php,” containing the code fra the “old” single.php. I try to open a blogpost, and this is my error:
Warning: Division by zero in /home/secondpo/www/baredritt/wp-content/themes/FuckingNewspaper/single.php on line 9 Warning: include(/home/secondpo/www/baredritt/wp-content/themes/FuckingNewspaperphp?): failed to open stream: No such file or directory in /home/secondpo/www/baredritt/wp-content/themes/FuckingNewspaper/single.php on line 9 Warning: include(): Failed opening ‘/home/secondpo/www/baredritt/wp-content/themes/FuckingNewspaperphp?’ for inclusion (include_path=’.:’) in /home/secondpo/www/baredritt/wp-content/themes/FuckingNewspaper/single.php on line 9
I don’t know what I could do with this… Perhaps you could help me out here? :)
- Thanks in advance!
October 25th, 2008 | 5:57 pm
To be a little bit more specific this is what I have in my single.php file when I get the error-message above:
post;
if ( in_category(‘5’) ) {
include(TEMPLATEPATH . ‘/hei.php’);
} else {
include(TEMPLATEPATH . ‘/hallo.php’);
}
?>
I am not a php-champion, so I am just not even sure if this is correct.. :(
October 25th, 2008 | 6:06 pm
Sorry for just spamming up everything here, but I actually had to use just:
post;
if ( in_category(‘5’) ) {
include(”hei.php”);
} else {
include(”hallo.php”);
}
?>
to make everything work. :)
November 5th, 2008 | 9:23 pm
Ready to argue with the themes of education-all. All the same, you can very well write about it
November 11th, 2008 | 10:53 pm
What happens if you don’t have a single.php file in Wordpress? I honestly don’t see one…
November 20th, 2008 | 5:00 am
Your a legend, cheers!
December 9th, 2008 | 9:21 pm
I was trying to figure out how to do this and found your site while searching the net for solutions. Worked perfectly. Thanks a lot!
January 11th, 2009 | 9:21 am
well i will try it out and see the result
..but…i have a custom template from my old site, isnt there any code you will want to include or require that should be posted on in your template for article to show?
March 5th, 2009 | 8:38 pm
Very nifty!
thanks!
April 10th, 2009 | 5:15 pm
Perfect, just what I needed. Sometimes a clear, simple and sweet solution is sought after and hard to cut through all the clutter from some bloggers. Thanks Matt!
April 20th, 2009 | 10:18 am
This is a very simple explanation. Clear and to the point. Thanks! :)
June 24th, 2009 | 6:44 pm
[...] more here: How to Set Up Custom Wordpress Category Templates in Four Easy Steps Share and [...]
August 22nd, 2009 | 2:38 pm
[...] Furthermore this method can quickly bloat your single.php file. So if you find you have more than three categories of posts that require a unique template I suggest creating a template file for each category post and using single.php to load the correct template. This method is explained by Matt at mattmedia.net. [...]
September 19th, 2009 | 5:18 pm
Stunning blog and good article. High 5 for u man !
September 25th, 2009 | 1:37 am
would be convenient to have a drop-down template-picker in the page/post editor. i think there’s a plugin for that.
and a “template” control added to the category editor inside wp. i think there’s an editor for that too.
and finally, a graphic gui-editor. still researching that.
September 28th, 2009 | 12:42 pm
Thank you for this – helped me a lot
October 22nd, 2009 | 12:15 pm
I had the same problem as Atle had (scroll up to October 2008). His solution solved it for me as well.
Also, there is a single-quotation character problem if you copy the code from above in the tutorial directly (surrounding the cat id number). With that cleared up, it works great.
Thanks for the tutorial and the helpful comments.
November 15th, 2009 | 3:58 pm
Thanks! I’ve been looking everywhere on how to do this. Much appreciated!
November 17th, 2009 | 3:59 pm
I haven’t been able to get this to work. And I would imagine that with the newer version of Wordpress you would need to modify the index file not the single.php file?
December 18th, 2009 | 1:36 am
I’m with Mark.
I haven’t been able to get this to work.
I’d like to know if this is only a viable solution with older Wordpress versions.
p.
January 6th, 2010 | 2:29 pm
This is a very good stuff man. But you can be more specific next time. See ya !
January 27th, 2010 | 7:04 am
It’s fantastic. Great tutorial :-)
February 3rd, 2010 | 11:21 pm
Oh My! I never thought this would be so easy. After a quick search with “change the template of a wordpress post”, I fell on this post and it worked perfectly in 5 minutes. Could not be happier. Thanks A Lot!
February 15th, 2010 | 4:25 am
Thanks for this – I’ve bookmarked it on Del.icio.us!
Even though there are plugins to change templates around, this method is nice and simple. It is better to try and standardise how templates are used, so I think it is reusable enough to use the template itself as a ‘traffic cop’ :)
April 1st, 2010 | 6:47 pm
This is a great way to unlock the potencial of Wordpress. Thanks for sharing this. UltraSnow
April 3rd, 2010 | 1:34 am
When I copied your code into my php editor, some of syntax was incorrect. This may be why quite a few people are having problems with this code. Folks copy this instead:
post;
if ( in_category(’9′) ) {
include(TEMPLATEPATH . ‘/single2.php’);
} else {
include(TEMPLATEPATH . ‘/single1.php’);
}
?>
——————–
the difference is that his code uses this (?) instead of (’)
April 5th, 2010 | 6:47 pm
Matt,
Could you apply this to the archive.php page to display two different Archive templates depending on what category they’re in?
April 8th, 2010 | 1:51 am
i tried implementing the code and it almost works… here is the code I used for the archive page:
post;
if ( in_category(’4′) ) {
include(TEMPLATEPATH . ‘/archive_sub_projects.php’);
} elseif ( in_category(’3′) ) {
include(TEMPLATEPATH . ‘/archive_sub_more.php’);
} else {
include(TEMPLATEPATH . ‘/archive_no_sub.php’);
}
?>
I then created those three other pages. The problem I am having is that when there is a category ID of 5 or 1 or 2, it doesn’t use the archive_no_sub. It uses one of the others that are specified for ID’s 4 or 3. What am I missing here?
I’m using 2.9.2
April 8th, 2010 | 1:53 am
post;
if ( in_category(’4′) ) {
include(TEMPLATEPATH . ‘/archive_sub_projects.php’);
} elseif ( in_category(’3′) ) {
include(TEMPLATEPATH . ‘/archive_sub_more.php’);
} else {
include(TEMPLATEPATH . ‘/archive_no_sub.php’);
}
?>
April 11th, 2010 | 11:28 am
This is perfect. Thanks! I will spread the word about your site. Have a beutiful day.
April 30th, 2010 | 6:46 am
Hi:
Thanks for the support on the subject. I am a journalist and I would be pleased if you could answer my query in simple layman terms:
I have over 100 categories in my eNewspaper http://www.indicpost.com. Now, while I have managed to successfully change headers for all the 13 pages I have, I am stuck at assigning the page header to the posts that belong to the categories falling under a page header.
I mean, for example, if I have 10 categories UNDER THE PAGE “Art & Entertainment”. Now, I wish to have ALL POSTS of ALL THOSE 10 CATEGORIES to have the header (’header_artentertainment.php’) which the parent page has.
Can you please guide me as to what code to put, EXACTLY where?
Thanking you in advance,
Best Regards,
Anshuman Rawat
May 27th, 2010 | 6:29 pm
Finally found such good tutorial to change category templates..U saved me, thnx:)
July 8th, 2010 | 12:51 am
It’s staunch that having pimples and blemishes on your give out can be embarrassing.
Acne lowers your confidence on and this can touch your school, profoundly, and engender life.
You get like person is looking at your swelling or blemish.
You endure proper like staying home ground!
Acne is known as pimples, lumps, and plugged pores that arise on the give out, neck, obverse, shoulders and chest areas.
There is not one main fact that causes acne and it is stimulated not later than hormones, pressurize, nubility, eatables, and other factors.
The small items can also dry out the outer layer of your coat encouraging your sebaceous glands to start producing more oil.
No one is protected to hull blemishes when the conditions are there.
Drug has produced diverse products to assistance relieve your acne. They are also positively a insufficient spontaneous remedies.
Here are some everyday habitual solutions that may slacken up on your acne.
Earliest you destitution to start eating best and desist from eating foods packed with sugars, fats, and oils.
Fried edibles liking not barely tender on the pounds but also may give rise to your acne worse.
Drinking a drawing lots of water longing also help. The water see fit excite the toxins that are causing the acne at fault of your body. You
You should carouse at least 24 ounces per day.
Another solution is to delete apricot essence on your face for the sake of at least 10 minutes a day. This sensible product make help blameless your outer layer of pimples.
Toothpaste is also a cyclopean something like a collapse to get rid of skin blemishes. You should set-back the toothpaste into the effected areas and hop it it beyond night. Then get rid of is off in the morning.
If the natural settling does not work there are a ton of products on the market.
One product that seems to suffer over the support is Proactiv Solution .
The Proactive Conclusion veneer disquiet products provide a three fitting for system to disburdened your skin.
It is available online or at your town retail store. There are diverse celebrities who swear past the product.
Proactive Mixture is also less budget-priced compared to other less fruitful products.
There are severe things your can do to bar your acne from occurring in the basic place.
Always be untroubled with your face. Latin aqua that is too simmering or cold can trigger your sebaceous glands to remaining cause unguent and clog up your skin.
You should bathing your clad at least twice a day to tend the bacteria levels to a minimum.
Do not touch your face. The hands proceed the most bacteria and you do not to part of the country the bacteria here.
You should also sponge off your hands sundry times a day. This choice pirate victual the bacteria levels ill in lawsuit you come up your face.
In place of women who utter makeup get into oil generous or hypo-allergenic makeup in the service of subtle skin.
August 6th, 2010 | 3:02 am
You sir are a champion! Thanks for this, it helped with a current project.
August 31st, 2010 | 11:28 am
Thank you so much! Your time is much appreciated!
September 1st, 2010 | 8:22 am
sweet i can now convert my site from static html to a wp cms