Tips Apply to the Full Version of WordPress.
I had a unique challenge. I needed to assign a specific stylesheet for only one category of blog posts in a WordPress blog. There are a lot of ways of doing this, but I wanted it to be fast and simple. I choose to use a WordPress conditional tag to check which category the blog post was in, and then change the header of the post to the one with the customized stylesheet for that particular category.
My very popular series on CSS Experiments in Design consists of almost a dozen pages with hundreds of different design experiments. Most of these feature inline styles, but a lot of them had their own styles in a separate stylesheet. The stylesheet was huge. With about a thousand articles on my site, why should I include over 30K of styles in my site’s default style sheet when I only need them for a handful of articles?
I needed a way to let the style sheet for the CSS Experiment pages only appear on those web pages and not the rest of the site. This is one method. In Using WordPress Categories to Style Posts, guest blogger, Abhijit Nadgouda of ifacethoughts, explains a similar method that might be easier for some.
With only one header template in my WordPress Theme, and the conditional tags saying “if this is a single page, show the single page”, I needed something that said:
If this is a single page in the X category
show the single page with these styles added.
By default usage, the WordPress Template Hierarchy states that when you click a link to a single post page, WordPress will automatically look for the single.php template file and if it doesn’t find it, it will look for the index.php and return the information in there for displaying a single post.
What I wanted was to throw a condition in the single.php that says “if this post belongs to the X category, do something different.”
The If in_category Conditional Tag
The process began by making two back up copies of the single.php page called single1.php and single.2.php.
Inside of the original single.php, delete everything and replace it with this:
<?php
$post = $wp_query->post;
if ( in_category('9') ) {
include(TEMPLATEPATH . '/single2.php');
} else {
include(TEMPLATEPATH . '/single1.php');
}
?>
In the most simple terms, the PHP code issues a query that says:
Check the post. If the post is in category ID number 9, display
single2.php. If not in category ID number 9, displaysingle1.php.
In the in_category(), we set the category ID number to 9, the one that holds all of my web page design articles and experiments. When the user visits any post within that specific category, the custom stylesheet is used for those blog posts.
This is just the start of what you could do. To showcase different results in different categories, you could create a long list of conditions like this:
<?php
$post = $wp_query->post;
if ( in_category('9') ) {
include(TEMPLATEPATH . '/single9.php');
elseif ( in_category('12') ) {
include(TEMPLATEPATH . '/single12.php');
elseif ( in_category('42') {
include(TEMPLATEPATH . '/single42.php');
} else {
include(TEMPLATEPATH . '/single1.php');
} }
?>
In my two “single” copy template files, I put a comment code in the top of each one with a number as a reminder of what each one was to do, like this:
<!-- single 2 - for CSS Web Page Articles -->
Since I don’t want to change these two different single post templates, just add the additional style sheet to the second one, I created two header template files, exact copies like with the single.php, with an extra style sheet link in the top of the second one.
Inside of header2.php in the head section, I added the second style sheet link:
<style type="text/css" media="screen">
@import URL('/wp-content/themes/mytheme/style.css');
@import URL('/wp-content/themes/mytheme/cssstyles.css');
</style >
In the new single.2.php template file, I changed the GET for the header to get the header2.php:
<?php
/* Don't remove this line. */
require('./wp-blog-header.php');
include(get_template_directory() . '/header2.php'
?>
To test this, I uploaded all the files and clicked on any post NOT within category 9. Clicking View Source in the browser, I hunted for my comment tag and “single 1″ or “single 2″ in the code to see which “single” template was used. If it worked, I should see a comment that says:
<!-- single 1 - for all the rest of the pages -->
If I see “single 2″ then something is wrong.
Then I clicked on a single post IN category 9 and did the same thing. There I should see the comment that this is indeed “single 2″ and the two style sheet links should be in the header as proof that everything is done right.
There are many ways of doing this, as the PHP and conditional tags and template files used by WordPress are so versatile, but this was very easy to do for someone who is lacking in much PHP skill, though I’m learning the hard way. From this, you can make as many single post page looks as you want, as long as they are styled by their category.
Here are some other resources that will help you with WordPress queries and the WordPress Loop, as well as developing, designing, and customizing your WordPress Theme.
- The WordPress Loop
- The WordPress Loop in Action
- WordPress Conditional Tags
- Understanding the WP_Query in WordPress
- WordPress Customization – Alphabetizing Posts
- Designing a WordPress Theme – Building a Sandbox
- The Secret of Successful Editing of WordPress Themes
- WordPress Tips and Tricks for Template Files
- WordPress Tips and Tricks for Style Sheets
- Designing a WordPress Theme From Scratch
- CSS: Studying Your CSS Styles
- Finding Your CSS Styles in WordPress
- Using Author Template Tags Outside of the WordPress Loop


Site Search Tags: wordpress tips, wordpress theme, multiple categories, different categories, changing stylesheets, web page design, wordpress design, theme design, conditional tags, wordpress tags, wordpress conditional tags, wordpress customization, category customization, category styles, single post styles, css, stylesheet
Subscribe
Subscribe by Email
Copyright Lorelle VanFossen, member of the 9Rules Network, and author of Blogging Tips, What Bloggers Won't Tell You About Blogging.












40 Comments
Thanks a lot for this post. I missed the function
in_category() and did some strange things to get the different customized posts. I have to rewrite lots of pages soon, since this is faster.
I’m waiting for a
switch($category){
case ‘1′:
require(“post1.php”);
break;
case ‘2′:
require(“post2.php”);
break;
default:
require(‘post.php’);
break
}
Just thought I’d drop you a line to say, this WordPress article really saved my bacon on the appropriate commands for issuing a second call to a different header file to the WordPress hard-coded one. Very, very appreciated, easy to understand, the code samples in particular came in very handy. Ahh, if only all tutorials were like this one. Keep up the good work!
Cheers!
Martin K.
Australia
http://www.urbanzombies.com
Thank you, this one had me stumped for a little while, I appreciate the tutorial!:)
Thanks for the helpful tutorial. This is exactly what I was trying to do, and couldn’t figure out how to have more than one header file.
This is exactly what I have been looking for, but I kept skipping it in Google because the title didn’t seem to be the right thing…
Thank you for the article and it really saved my day.
Just small remark I believe there are some missing closing braces or curly brackets before each elseif in the second php post query.
Great blog and thanks again.:):):).
I will keep coming to your blog and hopefully participate.
Thanks. For two years, no one noticed this. Thank you!!!!
Perfect. This really helps with my twitter posts!
Thanks for the tip, like Mohamed says, the code for the second query has some missing brackets, here’s the working code
post;if ( in_category('1') ) {include(TEMPLATEPATH . '/single1.php');}
elseif ( in_category('2') ) {include(TEMPLATEPATH . '/single2.php');}
elseif ( in_category('3') ) {include(TEMPLATEPATH . '/single3.php');}
else {include(TEMPLATEPATH . '/single1.php');}
?>
cheers, and thanks again, and again…
Thanks for this tip. I am using it to display one of two different sidebars, depending upon the post category.
Initially the code didn’t work for me–I had to change “in_category” to “is_category.” Now it works like a charm!
Thanks for all your great articles. Your blog is on my WP hot list now!
Adrienne
@Adrienne:
Interesting. There are two Conditional Tags in WordPress that deal with categories:
in_categoryandis_category. The first one asks if this “is the category” and then responds accordingly with the command. The second one asks if the post is “in the category” and responds. This worked for me in older versions of WordPress and I will be running new tests on this code in new versions soon, so I’ll double check that.Either one should work in this instance but I’ll look into this more. Thanks!
Lorelle,
Thanks for your reply. As I am still trying to work this out I am having mixed results with both methods. Part of the problem may be that I am trying to use two separate post sections and create sidebars that only pull up items for the separate areas. To do this I’ve created two large categories, let’s say a “Blog” category & a “Reviews” category, then put everything else in subcategories of Blog or Reviews. The test site resembles a traditional static site, with mostly static pages (including a static homepage), and includes these two separate posting categories as pseudo-pages.
It’s a bit of a stretch given my rather limited ability with WP, but I’d really like to make it work as I think the project has potential.
Adrienne
@Adrienne:
Just remember, you don’t have to break the wheel to invent the wheel. Forcing a blog into a “traditional” static website defeats the benefits of a blog. And too many bloggers and designers put too much emphasis on the front page when people land most on single post pages.
Good luck, but consider going forward instead of backwards in your web design.
Lorelle,
Your observations are very much appreciated. The site I’m creating isn’t a blog per se–it has blog-like elements, but it’s primary purpose is not as a blog. Whether or not the site has a static front page isn’t the issue I’m terribly invested in, anyway. What I’m looking for is a way to use WP to deal with a certain amount of a site’s information dynamically without having everything dumped into one big “blog bucket.” Perhaps I AM breaking the wheel here–I like to think of it more as exploring the possibilities of WP as it can be combined with/adapted to more traditional website structure.
See the comments in trackback No. 1, above–what I’m looking for is very similar to what that person is describing. I actually have two clients right now who want to utilize a “separate but equal” policy with a certain amount of their dynamic site content, and as I have been researching this I’ve found several other folks who are looking for exactly the same thing. So I see a need for this, at least with what I’m working on these days.
Thanks again,
Adrienne
What the trackback is talking about is common and explained here and in the WordPress Codex article on Conditional Tags, as well as elsewhere in the Codex, the online manual for WordPress users. You’ll find it is a very common usage, if what they describe is what you are looking for.
Good luck with it and let me know how it turns out.
Lorelle, thank you so much for clearly and concisely describing the problem and solution. I just began working with WP on a pro-bono project for a local charity, so I am very interested in quick and elegant solutions to minimize my non-billable hours. I am very thankful to have found your site. I easily implemented your suggestions to produce a consistent interface for single posts, by specific category. This was done in conjunction with specific page templates and sidebar templates, in order to present a consistent interface for each type of category.
I used this technique and accomplished exactly what I needed. It’s super handy for calling alternate pages outside of The Loop.
Now my question is, is there a way to make this work for multiple categories? in_category doesn’t seem to work except for single categories. I tried:
post;
if ( in_category(14) && in_category(3) ) {
include(TEMPLATEPATH . ‘/single_current.php’);
} else {
include(TEMPLATEPATH . ‘/single_back.php’);
}
?>
But it didn’t seem to work. Is there a way to call multiple categories using this technique? Any tips would be greatly appreciated!
The examples for how to use multiple in_category examples is found on the WordPress Codex Template Tags in_category article.
This worked great my category page here Lorelle! (http://fbcwaynesboro.org/archives/category/sermons)
One additional thing trying to figure out is changing the url structure a little. (changing term category to articles…)
Can permalink structure be set to load without the default “archive” without throwing everything off?
@ David Stembridge:
See Using Permalinks for more information on this, and if you are using the latest version of WordPress, it now features automatic URL redirects to redirect content around if you change your permalink structure.
Thanks for this article. I couldn’t for the life of me figure out how to display different comment pages. So instead of using it for the single.php, I’m using it for the comments.php. Some of my categories I have set up for reviews and this works great for giving a different look based on category id.
Hi, on the question “How to make multiple categories?” Here is the way:
if ( in_category('23') || in_category('830') || in_category('828') || in_category('829') ) {
include(TEMPLATEPATH . '/single1.php');
} else {
include(TEMPLATEPATH . '/single2.php');
}
@ Igor aka prodigy2m:
This is the new method that works with new versions of WordPress. The method in the article is for the very oldest versions of WordPress.
Also, in the future when posting code in comments and blog posts, please read Writing and Publishing Code in Your WordPress Blog Posts for tips.
Hi Lorelle! I’d like to go a step further, and apply a different template to posts in a specific category.
Here’s what I’m trying to do: I have an About page for a think-tank, which lists, below the usual about info, a list of the group’s experts & a short bio for each. What I’d like to do is link each person’s name/photo to a “page”, with a more complete bio & list of published works. I decided to go with “posts” instead of pages for each expert, because it seemed simpler to deal with. (I could be wrong; definitely open to suggestions.)
So, for every post in the “experts” category (category 6), I’d like the template used to display just one post, and none of the usual metadata or the comment form. I first tried to create a category-6.php file, but that’s only called when I click on the “experts” category; the posts themselves come up under the usual single.php template.
How can I make all posts in a given category display in a given template??
Thanks for your tireless assistance to all us aspiring WP-Pros!
Shane
@ Shane10101:
Author Templates in the WordPress Codex will help you solve much of this issue. I always start with the WordPress Codex, the online manual for WordPress Users, for technical help with WordPress.
Has anyone encountered pagination problems when using this technique?
i am using this technique for category pages as well as single post pages which is where i’m having the problem
I had pagination problems when excluding some categories from my “index.php”. The pagination simply disappeared. I solved the problem by commenting out the old “wp-pagenavi” code in my “functions.php” and installing it as a plugin instead.
Outstanding I have mods installed that made certain page like standard posts have items that should not have been there. With this work around it fixed the problem perfectly.
Thank you for suppling this
thank you, i will try it on my blog, wordpress is really capable of doing everything!
Thank you, thank you, thank you. Once again, you are my hero.
thanks for your informative hack I used the simple one
post;
if ( in_category(‘9′) ) {
include(TEMPLATEPATH . ‘/single2.php’);
} else {
include(TEMPLATEPATH . ‘/single1.php’);
}
?>
and with the help of the category-9.php implementation everything is fine for single and categories I have unique presentation for my 2 major things of my site news and products the problem is how can I change the first page index.php in order to show differently news and products.
This post was a LIFESAVER for me! Thank you so much!
Thanks so much, this was super handy! Just what I needed and easy to implement. You should have seen the ridiculous code I was trying to use to generate the page with a jillion if/then conditionals for the category haha.
Just exactly what I’ve been looking for.
I’m trying to somewhat “combine” the themes that I am using right now. A few fixes in each themes CSS and I can have, let’s say for example, a total cool Single Post Template for Photos and a regular one for normal posts
There’s a plugin that’s been out there for a while that does something similar… it allows you to create a custom single template for all posts within a specific category. It’s very easy to use. You can find it at http://guff.szub.net/2005/07/21/post-templates-by-category/.
I’ve been using it for a long time now, and it works with the latest versions of wordpress (for me anyway).
Great.Thank you very much
Thanks for this simple but usefull solution!!
much more elegant than the solution i was brewing in my head! thanks
Fantastic post and solution. I had installed a plug-in to do this (which worked really nicely, incidentally). It would have been fine if I was the only user of the site, but it’s a shared CMS-like site and I’m certain some users would never remember to select the correct template. This nicely takes the choice out of the contributor’s hands and automates the whole process. Thank you and keep up the good work!
Chris
Try the body_class() and conditionals now people.
Goood post though, prompted me to rethink what I was going to do.
Thanks,
L
39 Trackbacks/Pingbacks
[...] So, on to implementation. The Village Church uses Pages pretty extensively for our static content (such as the About section), which were able to reproduce the pretty URLs we had set up with the old site. Aside from the Contact form I mentioned above, the News and Sermons are the only Post content we have on the site. We’re using Categories to determine where a post should appear: if it’s News, drop it on the homepage, if it’s a Sermon, drop it in the Sermon archive. We also have put conditions in the individual archive pages to change the display, based on what category we’re looking at (here’s a helpful article on that). That way, Sermons and News items don’t look like each other. We’ve also set up a Featured category (which is a child of Sermons) which floats a copy of the sermon information to the top of the page, making it easy to feature or un-feature content. There is also a little include file that show the latest Sermon on the homepage (using WPDB). [...]
[...] 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 [...]
[...] to be style1.css, and the stylesheet of the “Tutorials” category to be style2.css. Lorelle provides a simple solution by following the directions [...]
[...] 分类下面的日志使用style1.css样式表, 而 “Tutorials”分类使用style2.css样式表. Lorelle [...]
[...] in a category. Ugh, there went my custom sidebars and headers. I then altered my single.php file according to Lorelle and created three single templates for each of the three categories (sidebar-6.php, sidebar-8.php, [...]
[...] Creating multiple single posts for different categories [...]
[...] Creating multiple single posts for different categories [...]
[...] Crea multiples posts para diferentes categorías [...]
[...] 27. Crear post múltiples para diferentes categorías [...]
[...] Creating multiple single posts for different categories [...]
[...] Crea multiples posts para diferentes categorías [...]
[...] Crea multiples posts para diferentes categorías [...]
[...] 27. Creating multiple single posts for different categories [...]
[...] Creating multiple single posts for different categories [...]
[...] Crea multiples posts para diferentes categorías [...]
[...] He encontrado unos trucos muy iteresantes para modificar el wordpress aqui, de donde me ha resultado muy util uno en especial, el de cargar distintas hojas de estilo según la categoría. [...]
[...] Creating multiple single posts for different categories [...]
[...] categories. I won’t give any further instructions; you’ll find everything you need in this beautiful tutorial by Lorelle. 2. Styling certain single postsI won’t explain this technique either, because Jean-Baptiste [...]
[...] 27.为不同的分类创造不同的单独日志页面 [...]
[...] Creating multiple single posts for different categories [...]
[...] Creating Multiple Single Posts for Different Categories [...]
[...] Creating multiple single posts for different categories [...]
[...] 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: [...]
[...] 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 [...]
[...] 27.为不同的分类创造不同的单独日志页面 能为你发表到WordPress博客不同分类的文章定制各自特定的样式。 [...]
[...] 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 [...]
[...] 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 [...]
[...] Creating multiple single posts for different categories [...]
[...] 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 [...]
[...] Creating multiple single posts for different categories [...]
[...] Creating multiple single posts for different categories [...]
[...] Today, while trying to customize the single.php template for a specific category I found a pretty old article written by Lorelle: Creating Multiple Single Posts for Different Categories « Lorelle on WordPress. [...]
[...] my previous post I talked about a Lorelle blog post on creating single post templates for different [...]
[...] Crea multiples posts para diferentes categorías [...]
[...] 27.为不同的分类创造不同的单独日志页面 [...]
[...] Creating multiple single posts for different categories [...]
[...] Creating Multiple Single Posts For Different Categories [...]
[...] Creating multiple single posts for different categories [...]
[...] Crea multiples posts para diferentes categorías [...]