Skip navigation

Using WordPress Categories To Style Posts

WordPress ThemesBy Abhijit Nadgouda

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.

37 Comments

  1. Posted September 6, 2007 at 10:26 am | Permalink

    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?

  2. Posted September 6, 2007 at 7:21 pm | Permalink

    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.

  3. Posted September 6, 2007 at 10:23 pm | Permalink

    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.

  4. Posted September 6, 2007 at 11:40 pm | Permalink

    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.

  5. Posted September 6, 2007 at 11:41 pm | Permalink

    Ah, that’s right. The functions.php comes 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!

  6. Posted September 6, 2007 at 11:55 pm | Permalink

    Thanks Abhijit – now I’m really excited! That is such an amazing functionality and can be used for so many things…

  7. Posted September 7, 2007 at 2:36 am | Permalink

    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?

  8. Posted September 7, 2007 at 3:56 am | Permalink

    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.

  9. Posted September 7, 2007 at 6:26 am | Permalink

    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.

  10. Posted September 7, 2007 at 7:50 am | Permalink

    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.

  11. Posted September 10, 2007 at 10:22 am | Permalink

    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)

  12. Posted December 8, 2007 at 2:38 am | Permalink

    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.

  13. Posted December 13, 2007 at 9:27 am | Permalink

    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

  14. Posted December 13, 2007 at 10:56 am | Permalink

    @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.

  15. Posted December 13, 2007 at 12:37 pm | Permalink

    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.

  16. Posted December 13, 2007 at 4:41 pm | Permalink

    @Gabe:

    Excellent! Thanks.

  17. Posted December 14, 2007 at 1:31 am | Permalink

    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.

  18. Posted January 2, 2008 at 11:40 am | Permalink

    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

  19. Posted January 2, 2008 at 12:07 pm | Permalink

    @ 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.

  20. Posted February 15, 2008 at 12:06 pm | Permalink

    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

  21. Posted March 12, 2008 at 8:44 am | Permalink

    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?

  22. Posted March 12, 2008 at 1:12 pm | Permalink

    @ 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.

  23. Posted April 2, 2008 at 5:21 am | Permalink

    hi guys, is there a way to creating multiple parent categories?

  24. Posted April 2, 2008 at 12:18 pm | Permalink

    @ 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?

  25. Posted June 10, 2008 at 9:17 am | Permalink

    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

  26. Posted June 10, 2008 at 11:28 am | Permalink

    @ 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.

  27. Posted June 10, 2008 at 1:32 pm | Permalink

    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

  28. Posted October 6, 2008 at 3:08 pm | Permalink

    please delete my previous messages.
    i want to place the content of my index.php so u can tell me where to put the the_category_unlinked line but it doesnt work out.

    sorry for messing up.

    greetz,
    Jonathan

  29. Posted October 6, 2008 at 6:52 pm | Permalink

    @ Jonathan:

    For help on WordPress issues, see the WordPress Support Forum first. To publish code within a WordPress blog post, comments, and in the WordPress Support Forum, see Writing and Publishing Code in Your WordPress Blog Posts. :D

  30. Posted October 6, 2008 at 8:43 pm | Permalink

    Hey Lorelle,

    Ive got the script working! Check it out: http://wdka.jonathansmits.nl/
    But I would like something more… :)
    The category items are now getting they’re individual classes but it does not automaticly add the right classes to the ‘last post’ links and also not the the Categorie links on the left of the homepage. The ones displayed next to echt post. How can I manage to get that done without adding more classes in my .css file? It would be so nice if there’s a way to let those categorie links use the same class that has been generated for the categorie items on the top-right of my blog.

    Thanx in advance!
    -Jonathan

  31. Posted October 6, 2008 at 10:06 pm | Permalink

    @ Jonathan:

    I don’t understand what you are talking about. You really need to get specific help from the WordPress Support Forum where someone can look at your blog and give you the help you need.

    There is no “automatic” method of labeling the last post links unless you are using a WordPress Plugin. Categories are automatically labeled by classes with their category ID number, but you have to add the classes to your CSS file manually. WordPress does not “automatically” put anything in your WordPress Theme’s stylesheet. You have to do that.

    I assume you need the various styles to style each category name. You have to add that information manually and style it to fit your needs in the stylesheet.

  32. Posted October 27, 2008 at 6:52 pm | Permalink

    Thanks for this, it is really helping get my head around all the WordPress PHP stuff.

  33. neil
    Posted December 25, 2008 at 1:53 am | Permalink

    what if the post appears in more than one category? how would you add a custom style to each post slug?

  34. Posted December 26, 2008 at 11:55 am | Permalink

    Using the WordPress Conditional tags to insert the category or custom style you want depending upon which category the post is in. However, are you talking about the post slug or the post title in the URL? Do you want something like example.com/categoryname/post-title/? to be in the URL or actually changing the post slug so it reads example.com/categoryname-post-title?

  35. Posted March 15, 2009 at 5:51 am | Permalink

    Hello there!
    Ok I think I am being dumb but it hasnt seemed to work for mine.
    I did everything as asked I think….
    Im no wordpress whizz so I find all this hard to explain.. but I was sure I followed your instructions to the T… can anyone help?
    I am using the sandbox theme at the moment and I havent touched the css file as I thought I would get the site functioning before I start designing the layout so please excuse the crude appearance.

    many thanks for any tips or help!
    Claire

  36. Posted March 15, 2009 at 5:54 am | Permalink

    no matter. got it working… my own dumb fault!!! thanks!!!

  37. Toby
    Posted May 4, 2009 at 11:03 am | Permalink

    Thankyou so much for this!


21 Trackbacks/Pingbacks

  1. [...] 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, [...]

  2. [...] 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 [...]

  3. [...] Using WordPress Categories To Style Posts has some very useful info on setting CSS classes depending on the category in which an article is [...]

  4. [...] a great article about Using WordPress Categories To Style Posts at Lorelle on WordPress [...]

  5. [...] 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, [...]

  6. [...] 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”. [...]

  7. [...] 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 [...]

  8. [...] 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”. [...]

  9. [...] This page shows quite easily how to style your posts based on category. ace. [...]

  10. [...] 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. [...]

  11. [...] 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 [...]

  12. [...] 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) [...]

  13. [...] Using WordPress Categories To Style Posts Saa poster ser forskellige ud alt efter kategori de er postet i (tags: wordpress css webdesign) [...]

  14. [...] At kunne style kategorier forskelligt [...]

  15. [...] Using WordPress Categories To Style Posts – Design ift. kategori Lignende indlæg [...]

  16. [...] Using WordPress Categories To Style Posts « Lorelle on WordPress [...]

  17. [...] categories. It’s not an approach that I’ve used before, so I’ll point you to Using WordPress Categories to Style Posts from Lorelle via a guest [...]

  18. [...] these two seem to be more of what i’m looking for. Styling Posts by Category and Category-Specific Images, using wordpress categories to style posts [...]

  19. [...] for them. There is another way to style different posts based on categories, which you can find at http://lorelle.wordpress.com/2007/09/06/using-wordpress-categories-to-style-posts/ which might be a better solution if you plan on having a lot of different [...]

  20. [...] 120. Using WordPress Categories To Style Posts [...]

  21. [...] Using WordPress Categories To Style Posts « Lorelle on WordPress [...]

Post a Comment

Your email is never published nor shared.