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…




65 Comments
Lorelle
October 9, 2007Another 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.
Andreas
December 14, 2007Dude! 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.
Andreas
December 14, 2007Dude! 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.
barbie
December 30, 2007Thanks for making this clear
barbie
December 30, 2007Thanks
santafeliving
July 19, 2008Hi – 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!
santafeliving
July 19, 2008Sorry, figured it out. Just one of those “duh” moments!
Selene M. Bowlby
August 5, 2008Works like a charm! Thank you so much for this!
Harald Johnsen
August 5, 2008That’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).
How to use WordPress as a Truly Customized CMS (Multiple Headers, Footers, Sidebars and more!) | Web Designer + Front-End Web Developer | Selene M. Bowlby
August 27, 2008[...] How to Resource Link… Creating Your Own Page Templates [...]
JamieO
September 10, 2008Another 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.
Carl
September 21, 2008Hi,
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
John
October 1, 2008Thanks 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.
another matt
October 20, 2008i’m getting lost on step 2….
oops.. i meant – thanks fella. Big help!
Viebrapreah
October 20, 2008Hey,
I am, John
Nice site, verry informative
check my site:
http://ARcA8NEZ.spaces.live.com/
Atle
October 25, 2008This is just one hell of a great post
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!
Atle
October 25, 2008To 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..
Atle
October 25, 2008Sorry 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.
Gradimir
November 5, 2008Ready to argue with the themes of education-all. All the same, you can very well write about it
Mark
November 11, 2008What happens if you don’t have a single.php file in WordPress? I honestly don’t see one…
Martin
November 20, 2008Your a legend, cheers!
Tim
December 9, 2008I was trying to figure out how to do this and found your site while searching the net for solutions. Worked perfectly. Thanks a lot!
valentine
January 11, 2009well 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?
suzy
March 5, 2009Very nifty!
thanks!
AndroidTapp.com
April 10, 2009Perfect, 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!
Carolina
April 20, 2009This is a very simple explanation. Clear and to the point. Thanks!
How to Set Up Custom Wordpress Category Templates in Four Easy Steps | New WP Themes - WordPress News
June 24, 2009[...] more here: How to Set Up Custom WordPress Category Templates in Four Easy Steps Share and [...]
Template all Posts in a Wordpress Category Automatically | JamesKrayer.com
August 22, 2009[...] 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. [...]
adamoerikom
September 19, 2009Stunning blog and good article. High 5 for u man !
johny why
September 25, 2009would 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.
Alan
September 28, 2009Thank you for this – helped me a lot
Jess
October 22, 2009I 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.
Getch
November 15, 2009Thanks! I’ve been looking everywhere on how to do this. Much appreciated!
Mark
November 17, 2009I 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?
phat
December 18, 2009I’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.
adamusxyz
January 6, 2010This is a very good stuff man. But you can be more specific next time. See ya !
Ivan
January 27, 2010It’s fantastic. Great tutorial
Diane Bourque
February 3, 2010Oh 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!
Joe
February 15, 2010Thanks 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’
UltraSn0w
April 1, 2010This is a great way to unlock the potencial of WordPress. Thanks for sharing this. UltraSnow
Orgie
April 3, 2010When 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 (‘)
Jason
April 5, 2010Matt,
Could you apply this to the archive.php page to display two different Archive templates depending on what category they’re in?
Jason
April 8, 2010i 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
Jason
April 8, 2010post;
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’);
}
?>
Joel Lundgren
April 11, 2010This is perfect. Thanks! I will spread the word about your site. Have a beutiful day.
Anshuman Rawat
April 30, 2010Hi:
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
Alex
May 27, 2010Finally found such good tutorial to change category templates..U saved me, thnx:)
adderaiterm
July 8, 2010It’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.
vince
August 6, 2010You sir are a champion! Thanks for this, it helped with a current project.
nike
August 31, 2010Thank you so much! Your time is much appreciated!
chris
September 1, 2010sweet i can now convert my site from static html to a wp cms
Zeus
September 13, 2010This does not work for me. What am I missing?
I seem to get warnings come up on page when i use your code or the suggested variations byb Atle or Orgie…
Please help.
Wordpress Tutorials for the Hobbyist Web Designer
September 23, 2010[...] 4. How to set up custom wordpress category templates in four easy steps – from mattmedia.net [...]
Jodie B
October 7, 2010I got this to work beautifully. However I do have one question.
Can this be configured to show a specific template for a list of blogs posts from a specific category?
My individual posts are coming up with the custom templates I assigned them but when you view a list of posts they are shown using the template I specified as “else”.
webdesignerslog
October 29, 2010Thanks for such a great code .. but i have one confusion … i have to place this code in single.php file… am i right??
yane
November 11, 2010http://wordpress.org/extend/plugins/category-templates/
bob
February 11, 2011so, what if your post is marked in two categories, ie, cat=4 and cat=8, and you only want it to display in the alternate template when it’s specified as cat=8…..that may sound confusing, but here’s what i’m doing:
it’s a site for a law firm…i have lawyers(category 4) listed in a drop-down menu, when you hover over the lawyer, it brings up another pop up containing a snippet of the lawyer’s profile…within that pop up, there is an link to view full profile, a link to email that lawyer, and a link to print full profile….the client has a layout he wants for all printed pages…a ‘print friendly’ version of the post..so, what i haven’t figured out how to do is to print the full post as the ‘print friendly’ version…
my thought was to create a category called ‘print’ that i could add all posts to which would be printed(category 8)….so, i put all the posts of the lawyers, and all the ‘practice areas’ (category 5) and added them to the ‘print’ category…..so, now they are all in 2 categories….
i was going to use the permalink for the ‘print’ category as the link on the ‘print’ icon in the snippets……but, when i do that using the code in this article, it also shows that category post template when i try to view the post(in category 4 and 5) any time on the site, not only when i click on the print icon…….ie, since the lawyers and practice areas are also in category 4/5 and 8(print category), no matter when i try to view any lawyer or practice area post, it goes to the custom print template….
know what i mean?
bob
February 12, 2011one last bit of clarification….the post is in two categories so it has two permalinks, ie, …/lawyers/robert and …/print/robert
i want to the first one to be displayed ‘normally’ and the second one to be displayed as the ‘print friendly’ version…..
but, no matter what/where, the post always comes up as the print friendly version…(because it is included in category
Kathy
April 5, 2011Hi, what if I want to apply this to categories?
Say, the category.php is the portal. Then when the person clicks on a certain category, the category.php portal registers which CATEGORY it IS, and calls the appropriate template for it?
Is this possible?
Thanks in advance.
Aline
June 2, 2011wow,
you just saved me!
thank you.
alessio
June 4, 2011works perfectly, thanks a lot
Wordpress As a CMS | Web Design Edmonton
November 26, 2011[...] How to Resource Link… Creating Your Own Page Templates [...]
WordPress Theme Creation
November 29, 2011[...] Tricks article on how to create your own CMS. If you decide to work within WordPress, however, this article might help for styling layout by category… something I’m considering myself now. [...]
jaouadnet
December 5, 2011Thanks for such a great code, but i have one confusion, i have to place this code in single.php file, am i right?
Matt P
December 6, 2011Hi jaouadnet… Yes, this would replace the single.php file altogether…