One of the reasons WordPress fits so many bills is its flexibility. It lets you do things at a much lesser cost, not necessarily money, but time and effort too, as compared to others. This article is about styling WordPress posts differently using the categories they are classified under.
Why Categories?
Categories are the metadata, they give you information about the post. This metadata can be from multiple aspects, e.g., using the category open source to convey that the post is on that subject or using the category feature to indicate that this is a researched feature as against a random post.
The categories contribute to the reason why WordPress suitable for so many non-blog web sites.
You can make this metadata more visible by styling the posts differently by categories - like a different background color or different icons or bigger font size.
The Wrong Way
Of course, you know the categories, you have the post and you have the if-else PHP command using which you can create different HTML code as per categories. It is quite easy to know if a post is classified in a specific category using in_category($category_id).
Everything is available and it is very tempting to use this. The only problem is that this can cause performance problems in future. Everytime an if-else is executed, processor cycles are spent in taking the decision. This can escalate to a severe performance problem if the number of categories increase.
The Right Way
So here is the solution I prefer. WordPress lets us control the styles purely in CSS, and the connector between the HTML code and the styles is the corresponding CSS class or ID. For example, consider the markup
<div class="post">
Here the CSS class post defines what styles will be applied to the post. I have omitted other code from typical templates to keep the space clean.
The best way to leverage this is to use the WordPress category slugs as CSS classes or IDs, and define styling for them in the CSS. Getting the category as slugs, and not as links, is not directly supported in WordPress today. But it is extremely easy to do so. You can put the following code in your theme, preferably in functions.php, so that it is available to all templates in the theme.
function the_category_unlinked($separator = ' ') {
$categories = (array) get_the_category();
$thelist = '';
foreach($categories as $category) { // concate
$thelist .= $separator . $category->category_nicename;
}
echo $thelist;
}
The corresponding index.php can look like
<div class="post<?php the_category_unlinked(' '); ?>">
This will create the following HTML code for a post classified in categories with slugs opensource and feature:
<div class="post opensource feature">
And now the styles defined in the CSS classes post, opensource and feature will be applied to that post. The corresponding CSS code can look like:
.post {
padding: 5px
}
.opensource {
background-color: #f0f0f0;
}
.feature {
font-size: 1.1em;
background-image: url(images/feature.png) no-repeat top right;
}
This thing to remember here is that the styles are applied in a cascading manner, so you have to be careful in duplicating the styles. For example, if you set the background-color for CSS class feature, it will override the one set in the class opensource.
Conclusion
You can go ahead and use the other metadata like author name and define corresponding CSS classes in your stylesheet. You can find excellent code for this in the Sandbox theme, in functions.php as a function called sandbox_post_class($print = true).
I have been using this technique for quite some time. If you do remember this, then you can leverage this to the fullest extent to visually style posts differently.
Abhijit Nadgouda is a software engineer who wants to use software to solve problems and contribute to the software development world. Blogging is the medium of his choice for developing and conveying his thoughts.











27 Comments
Excellent. I used a different technique to set up a conditional tag to switch headers via the template files, thus introducing a new header with a new stylesheet on a per category basis. Your technique is much easier, though it does involve changing the core programming files.
I wonder if there is a hook in there to create a Plugin to put this into the
functions.php?We will not need to change the WordPress core files. We will need to change the theme files though. functions.php is usually present in a WordPress theme.
I just want to make sure I understand what you’re describing here - are you saying that on a blog home page, we can have posts from different categories appear differently? Or are you talking about styling the category pages themselves, like when you click on a category name?
If you are referring to different categories on a blog home page, this is so amazing, and I am really excited, since that can be so helpful with sites that have “feature” articles, as you mentioned yourself.
Miriam, sorry if the post is creating a confusion.
“… on a blog home page, we can have posts from different categories appear differently …”
Yup, it is this one. You can style posts from different categories differently on the blog homepage, or for that matter on any page in the blog. This styling can be global throughout the blog, wherever you use the category slugs as the CSS classes.
For styling the category pages you can use different category templates.
Ah, that’s right. The
functions.phpcomes with the new Default WordPress Theme, so if the user doesn’t have it, they need to get it working in their own Theme…hmmm. Another topic! Hint, hint!Thanks Abhijit - now I’m really excited! That is such an amazing functionality and can be used for so many things…
Well, here’s a poser for you - how well will this work when WP2.3 goes gold and (aside from the utter tag/cat confusion) will it be easy enough to do this using a tag rather than a category or would the blogger need to employ both categories AND tags (the core tags, not UTW or similar) to use the functionality in this post?
Lorelle, true, functions.php is one of the things we take for granted.
Collin, I believe any metadata can be used for this purpose, which includes tags. You only need a way to retrieve the metadata for that post. Currently this code uses the get_the_category function to retrieve the categories. In the newer versions if this changes, we will have to change our code for that, otherwise there should be no problems.
Whether a blogger should use tags for styling is completely dependent upon him/her, rather completely dependent on how the categories and tags are used. But assuming that there will be a way to retrieve tags for a post, one can use the same technique with them.
I like this. There is a plugin or widget that does something similar, if I recall correctly. Downside: You have to be dilligent about using categories.
Missing: I would like to have a template for certain categories that includes not just style (style is handled by the method you describe here) but contents as well. For instance, a particular graphic in a particular location at the top of the post, and a particular bunch of text in the beginning and/or end of the post. I do this now with simple cut and paste, but I’d love to have a WordPress Post Editor that helps me to do this.
Greg: It will, but it’s a little bit challenging. If there is “space” and the text won’t cover the graphic, then you can put it in your stylesheet based upon the category, if your category template file is set up with category styles.
Otherwise, you do what I do and keep a text file of the different “badges” I use for different categories of posts and copy and paste them into each post. They are physically within the post content, so the text easily wraps around. It takes seconds, and I control which one goes where.
figured this solution would be ideal to replace the missing-in-action CategoryIcons plugin
wrap each post in a div with the particular category name as a class; would be better still if the category slug field can be called into a template (http://wordpress.org/support/topic/108241#post-599076)
I cannot agree that there is a right and a wrong way. I have just tried out both methods - ifelse and css-classes - and both have their advantages and disadvantages. The main point is that - in my eyes - only a combination of both gives you the power to really work with Asides/different categories: If you define an if-else-Block to filter just the categories needed to redefine the structure of your markup, but at the same time add all necessary classes, you can work with a highly optimized usage of processor cycles by at the same time no loss in editing power.
I wrote an article on that, however, it’s in German. But I think you get the idea through the code-samples. 3 Varianten, Asides in WordPress zu erstellen.
Hello,
This is an excellent method for styling the posts. Is it possible to apply corresponding classes to the Category links in my menu?
Thanks, Gabe
@Gabe:
If your WordPress Theme category links have CSS classes on them, anything is possible. The problem is that by default, the parent categories do not have individual classes, and the children categories are grouped under the “children” class. You can find or write a Plugin which might modify the WordPress category template tag to include category-specific ID or classes, or just edit your sidebar.php template file to list the categories manually, which would mean you would have to manually add or delete any category changes.
If you find an easy method, let me know. For the most part, a cluttered sidebar (or Theme in general) is not very desirable or usable, so I’m not sure how much this would be in demand. Check out the parameters in the wp_list_categories() template tag to see if there’s a way to customize this to meet your needs.
Hi Lorelle,
Thanks for the quick reply.
I found a great way to make this work.
In the classes.php file.
just change the following:
line 637
$class = 'cat-item cat-item-'.$category->term_id;TO
$class = 'cat-item link-'.$category->category_nicename;Then add classes in your stylesheet for link-category-name.
@Gabe:
Excellent! Thanks.
Excellent job done here! This write-up will definately be of help to users who have difficulty understanding the different php file that came with wordpress script.
i do that too. however, i’m new and
don’t understand why WordPress drops
the post out of the main frame after
someone comments…a little assist, please?
Condi
@ Condi:
I don’t know what you are describing. After you comment, the page reloads. The comment will be visible if the comment has not been moderated or caught as comment spam. If you are using a WordPress Theme that features “frames”, I’d change Themes. Does this happen when you change Themes anyway? It could be a problem with your WordPress Theme.
Please search for help on the WordPress Support Forums and ask there if you can’t find an answer. They usually have the time to visit your site and investigate.
Very cool, thanks! Had a little hiccup with it, didn’t put the “functions.php” code between the php tags in my file at first.
Nice way for me to mark up my automatic posts from del.icio.us. Now I can show them with a modified background
I want to style a single category title differently. I did get the above to work, only does this mean that everytime I add a new category I have to make sure I add a style for it in my css? How could I set a “default” style that is always active unless the post is filed under a the selected “styled” category?
@ Niles:
There are a lot of things you can do besides what I have listed here. You can use the Post Templates by Category WordPress Plugin. You could code it yourself using the techniques from Category Templates, Displaying Posts Using a Custom Select Query, Giving different styles to different WordPress categories, Conditional Tags, Sarah And Leo tips for designing their new Theme, and Category dependent post stylization.
hi guys, is there a way to creating multiple parent categories?
@ rex:
To create categories, use the Categories section in the Write Post Panel or under Manage > Categories. To rearrange how the categories are displayed on your blog, see Linking Posts Pages and Categories in the WordPress Codex.
Is that what you wanted to know?
Hello,
When i add the code to my functions.php file and update my theme files i get an error message,
why is this happening and how can i fix it?
thanx
@ Ali G:
The code did not appear but these questions are to be directed to the WordPress Support Forums where you will find the help you need.
I included a link to a imageshack screenshot i took, for some reason its not in my post now
“http://img260.imageshack.us/img260/2527/picture1ad1.png”
is the code in the functions supposed to be wrapped in any php tags? and is it compatible with the latest wordpress version? my functions.php was empty and that was the only code i had in there and it still didnt work
ill try the support forums too, thank you
16 Trackbacks/Pingbacks
[...] two month party is on, and this month it is about WordPress. I have used a nifty technique to use WordPress category slugs to use different styles for posts in different categories. It not only keeps the HTML code clean, [...]
[...] about WordPress! Abhijit Nadgouda has written a post on Lorelle’s blog explaining how you can apply unique styles to posts in different categories. He explains how you can use the category slugs to create styles that can be dynamically called to [...]
[...] Using WordPress Categories To Style Posts has some very useful info on setting CSS classes depending on the category in which an article is [...]
[...] a great article about Using WordPress Categories To Style Posts at Lorelle on WordPress [...]
[...] has an interesting post about Using WordPress Categories To Style Posts. I use it so far to get a different layout for my Asides category. It was fairly easy to set up, [...]
[...] Using WordPress Categories To Style Posts: Abhijit Nadgouda of ifacethoughts helps us customize any post by category, allowing you to change how a post is viewed on multi-post page views so it stands out visually by category “style”. [...]
[...] 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 [...]
[...] Using WordPress Categories To Style Posts: Abhijit Nadgouda of ifacethoughts helps us customize any post by category, allowing you to change how a post is viewed on multi-post page views so it stands out visually by category “style”. [...]
[...] This page shows quite easily how to style your posts based on category. ace. [...]
[...] Die Codevorlage zur Variante 1 (und eine genauere Erklärung als meine) findet sich bei Remote Sensing Tools. Die Codevorlage zur Variante 2 (und eine genauere Erklärung) findet sich bei Lorelle. [...]
[...] Nachteil der If-else-Abfrage bringt Abhijit Nadgouda auf den Punkt: Of course, you know the categories, you have the post and you have the if-else PHP [...]
[...] Using WordPress Categories To Style Posts « Lorelle on WordPress Found a way to change post styling in wordpress using the post’s category (tags: mycomments wordpress css html howto background) [...]
[...] Using WordPress Categories To Style Posts Saa poster ser forskellige ud alt efter kategori de er postet i (tags: wordpress css webdesign) [...]
[...] At kunne style kategorier forskelligt [...]
[...] Using WordPress Categories To Style Posts - Design ift. kategori Lignende indlæg [...]
[...] Using WordPress Categories To Style Posts « Lorelle on WordPress [...]
Post a Comment