Alister Cameron // Blogologist

Changing the world. One blog(ger) at a time.

Wordpress Plugin: ClassyBody

I love really smart CSS and am always on the lookout for a better way to do things. To that end I just love checking out the latest additions to CSS Zen Garden. This is a site that shows how amazingly you can take exactly the same HTML and create a completely different look and feel, based solely on different CSS. But there is one important matter…

Badly marked up HTML spells the death of CSS creativity. You’ll know what I mean if you’ve ever tried to mess around in MySpace. There is a reason why their HTML is devoid of classes and IDs, and why their CSS is somewhat cobbled… they don’t want you to be able to mess with their main page elements!

But CSS Zen Garden’s HTML is a good example of how to do it right, as is the website/blog of its creator, Dave Shea - Mezzoblue. Now speaking of that (and getting to the point of this post!), I noticed that Dave’s gone with a pretty funky colour scheme approach, where he stays with a particular colour scheme for a few months and then changes to a new one, based on the colours of a picture he chooses for the header. Great idea, and the design is really nice too.

mezzoblue.com

So being a Wordpress user, I wondered how I might achieve something similar, but purely in CSS (Dave passes a querystring parameter to his CSS file, which I assume is dynamically generated.) And this led me to something I’ve played around with before that’s very powerful: adding classes to the Body tag.

If you’re going to get smart about CSS, adding classes to your Body tag can add amazing power to what you can achieve in your CSS, since the body tag is the parent element of everything that is displayed on the page. So it follows that any class you add to the body tag is information you have at hand for any CSS styling you apply to any other HTML element on the page. Think about that for a minute.

How can this make Wordpress templates smarter?

Great question, dear Padwan Padawan. For my purposes I’d like to be able to change the appearance of any page element, purely in CSS, based on what kind of webpage my Wordpress blog is displaying. Along the lines of the “is_functions()”, I’d like to know when I’m on the homepage, a search results page, a single post, etc. Then I’m free to change the header image, or the page background, or perhaps change the dimensions of the sidebar, or whatever…

But I’d like to go further. I’d like a certain different look to pages related to one of, say, three different categories. Or I’d like all posts from December thru February to have a snowy/winter background theme (for you Northern Hemisphere-ites!).

So to cut a long story short, I created my first (yay!) Wordpress plugin that lets you do all of that, and whatever your imagination would like to do, thanks to the simple addition of classes to the Body tag. (Jumping ahead, I reckon this would make a very logical addition to the Wordpress core, but that’s something you can fight for or against in the comments.)

What does this plugin do?

ClassyBody adds contextually-relevant classes to your body tag. That’s it! What you do with this added power (and I do mean power) is only limited by your CSS skills. Look out for the next version of my site design, where I am planning to get into this a fair bit…

Since ClassyBody only adds classes to your Body tag, you can safely install this plugin without the fear that it will mess up your existing design, unless - by chance - you’re already adding classes to your Body tag. But if not, have no fear firing up this plugin. Its power will only come to the fore when you start messing with your CSS and taking advantage of it.

ClassyBody v1.0 conditionally adds the following classes to your Body tag:

Class Condition
home Your blog’s homepage.
page Any static page.
page-[ID] Any static page (eg. page-4).
post An individual (single) post.
post-[ID] An individual (single) post (eg. post-71).
category A category archive page.
cat-[ID] A category archive page (eg. cat-12).
archive A dated archive page.
[Month] [year] A given month’s archives or a single post (eg. March 2006).
search A search (results) page.
error A 404 (”page not found”) error page.

Why not do this in PHP (like some templates do it)?

Read my lips: PHP for “logic”, CSS for presentation. This is why ClassyBody uses minimal PHP processing (just once) to populate the opening Body tag with classes, and then leaves the rest up the CSS. It’s all that’s needed, assuming you’re prepared to put in a little effort with your CSS. No new PHP variables needed, no repeated function calls, no filling up Wordpress template files with more and more PHP. (This is for me all about a cardinal “mantra” I try to stick to: clean HTML with semantic markup, minimal PHP in the template files, as much of the presentation as possible in CSS. Never perfect, but this is the aim.)

Examples

The following examples are very simple and assume the naming convention of the Wordpress Default theme’s CSS.

Winter-themed posts. Want all the posts you wrote in Winter to automatically have, say, a snowy-background image? Try something like this (remembering to create and upload the image in question!):

/* a snow theme for winter posts */
body.December, body.January, body.February {
   background-image: url(’images/snowy-background.jpg’);
   }

Of course, if you’re Down Under like me, change the months accordingly.

Different header images. Want to have a special header image for each of the different sections of your blog? Try something like this:

/* the homepage */
body.home #header {
   background-image: url(’images/home-header.jpg’);
   }

/* static pages */
body.page #header {
   background-image: url(’images/page-header.jpg’);
   }

/* individual posts */
body.post #header {
   background-image: url(’images/post-header.jpg’);
   }

/* category archive pages */
body.category #header {
   background-image: url(’images/category-header.jpg’);
   }

/* dated archive pages */
body.archive #header {
   background-image: url(’images/archive-header.jpg’);
   }

/* search (results) pages */
body.search #header {
   background-image: url(’images/search-header.jpg’);
   }

/* 404 error pages */
body.error #header {
   background-image: url(’images/error-header.jpg’);
   }

Customise a specific category, post or page! You may not want to, but ClassyBody gives you the power to do it. For every category archive listing, and for every individual post, the ID is displayed as a class, in the form cat-[ID], post-[ID] or page-[ID]. This means you can change the appearance of any HTML element on any specific post, page or category listing. Just add the specific customisations to your CSS in the right places.

A live demo - sort of!

I have ClassyBody running on this site, although I have yet to take advantage of it, in CSS. But you can at least see by viewing the source of any page, what classes are being added to the Body. This may be the quickest way for you to see what is added and for it to make the most sense. Make sure to look at an individual (single) post page, as well static pages and a category archive listing.

(Note: If you use this plugin extensively on your blog, let me know and I can add your blog here as an example. Happy to do that for good exampled of usage!)

Is anyone else talking about classes in the Body tag?

Yes, and it’s been talked about for a long time. 37 Signals had a post about it, as did A List Apart, and Eric Meyer was talking about something vaguely similar in 2001!. But to the best of my knowledge there certainly is no Wordpress plugin for this, or the promotion of this approach for Wordpress templates in general.

Calling all Wordpress theme designers…

My personal hope is that more and more Wordpress themes will be released and/or retrofitted for this plugin, and that theme designers will take the opportunity afforded by this plugin to get more creative with colours, backgrounds and the CSS customisation of the different kinds of pages in Wordpress. Ultimately I’d hope to see this kind of functionality built into Wordpress core, even though it’s a relatively simple bit of PHP and can be hacked into header.php easily enough, even without my plugin (if you so desire).

Installation & Usage

This is a plain vanilla plugin and installs in the normal way:

  1. Download the latest version of ClassyBody.
  2. Change the extension of the downloaded file from .txt to .php.
  3. Upload the renamed file into your /wp-content/plugins/ directory.
  4. Activate the plugin.
  5. Replace the opening Body tag in your active theme’s header.php file with:
    <body class="<?php classybody(); ?>">
  6. You’re done. Now go fiddle with your CSS!

Version History

  • Version 1.1.20070202 (2 Feb. 2007). Added custom class feature using custom fields for posts and pages. Read this post for details.
  • Version 1.0.20070106 (6 Jan. 2007). Removed extra CR-LFs after closing PHP tag. Think they were causing errors for Jaynee (below) and others. Hope they’re fixed now. Sorry folks. Silly error on my part.
  • Version 1.0.20070104 (4 Jan. 2007). Initial public release.

28 Comments

Note: Commenter website links are not no-followed, in case
you were wondering... I believe in rewarding commenters!

  1. Posted 1 year, 4 months ago // Permalink

    Hi Alister,

    I love you man!! No Seriously! A designer who is thinking about CSS is a designer close to my heart. I am always preaching that CSS is the only way to code!!

    Great Post MAte

  2. Posted 1 year, 4 months ago // Permalink

    This is basically what the Sandbox theme does, which came out back in August of 2006.

    I actually wrote a crude version of a similar plugin the July before (Dynamic Semantic Classes but with Andy enhanced this to include classes for posts and comments.

    So yep, it’s a great idea.

  3. Posted 1 year, 4 months ago // Permalink

    Nice! You definitely make a convincing argument for adding this to a site. I’m going to try it out tonight and see what happens. Thanks for the plugin.

  4. Posted 1 year, 4 months ago // Permalink

    This is awesome.

    But I just thought I would mention…

    “Great question, dear Padwan.”

    If you’re going to make Star Wars in-jokes to a bunch of geeks, you’d better spell the reference right. ;) It’s “Padawan”

    Kidding aside, this is a seriously cool. The thing I love about CSS is that the simplest things can be sooo powerful. :)

  5. Alister
    Posted 1 year, 4 months ago // Permalink

    @Stephen - Of all the things to misspell!! I stand corrected and am making the change RIGHT NOW!

    Thanks for the good feedback too, everyone.

  6. Posted 1 year, 4 months ago // Permalink

    I’d love to use it, but I get the following error message when I activate the plugin:

    Warning: Cannot modify header information - headers already sent by (output started at /home/myname/public_html/wp-content/plugins/classybody.php:41) in /home/myname/public_html/wp-includes/pluggable-functions.php on line 272

    what am I missing?

  7. Alister
    Posted 1 year, 4 months ago // Permalink

    @Jaynee - good question! I had a similar error appear a few times here and there, but never on the public side, only on a few admin pages (which I couldn’t work out). I’ll fiddle for a while and see if I can reproduce it further… stay posted for a fix if needed (or advice - either way).

  8. Alister
    Posted 1 year, 4 months ago // Permalink

    @Jaynee - Show’s how little PHP I do… I left a few carriage returns after the closing PHP tag! That’s a bad no-no, but I’ve fixed it. Anyone experiencing issues should grab the latest version or just edit their file to remove the extra (blank) lines after the closing PHP tag, which looks like ?> (there should be absolutely NOTHING after that tag!).

  9. Posted 1 year, 4 months ago // Permalink

    All fixed! It loaded up fine once I took out those extra carriage returns. Now I just need to figure out how I want to configure my stuff! I can’t wait and will let you know when I’ve got it up.

  10. Posted 1 year, 4 months ago // Permalink

    Hey Al,

    Thought you may be interested in the new marketing sherpa marketing report. Didnt know if you were on their list so here is the link to download it if you want:

    http://wisdom.marketingsherpa.com

    Its not too bad for a free download
    Shaun

  11. Alister
    Posted 1 year, 4 months ago // Permalink

    Thanks mate. I’m having a look now…

  12. Posted 1 year, 3 months ago // Permalink

    This is exactly what I have been looking for. For my first website, I had to learn Flash (for an intro) then CSS for designing the pages..I ended up building three external CSS files to run three separate pages (one with side navigation) and managed to figure out the necessary hacks to make the site look as I wanted (www.killingjanefonda.com)…then I decided to blog….I know zip about PHP, have the desire to constantly change themes, but i have been only 10% successful in modifying any theme to suit my preference. I’ll be back to comment on this plugin once I apply it to my site (cllucas.com)

  13. bird
    Posted 1 year, 2 months ago // Permalink

    You. YOU! This is beautiful. Well done.

  14. Posted 1 year, 1 month ago // Permalink

    hi together

    where have i to put in “”>”

    here is a part of my current header.php-file

    /”>

    “>Home

    THANKS FOR HELP!

  15. Posted 1 year, 1 month ago // Permalink

    does not work with copy the header.php file in. why?

  16. Posted 1 year ago // Permalink

    Thanks for the Plug-In Alister. Will have a look :)

  17. Posted 10 months ago // Permalink

    Brilliant. I am in awe. I am not sure how I could have missed this post. This technique will be perfect for a site I am building where I want to retain the same overall look but need to distinguish between two or more distinct sections.

  18. Posted 10 months ago // Permalink

    Brilliant plug-in! I’m glad I stumbled across this - I can’t wait to give it a try on my mom’s environmental blog (love your idea of the “winter/summer” style changes - that’s what I’ll try first!). Thanks for sharing this with the rest of us geeks who aren’t yet capable of writing our own plugins - maybe someday I’ll write one worthy of sharing but in the meantime I appreciate yours.

  19. Posted 10 months ago // Permalink

    Great stuff. I normally use a custom body class to override the original theme’s CSS globally, but this takes it to another level. It will make my categories so much easier to customize.

  20. jj
    Posted 7 months, 2 weeks ago // Permalink

    can i have the code inserted depending on what category your in ? i’m trying to change out header images but also some headers have flash animations…..can i use the flash embed code with you plugin ?

  21. c boulanger
    Posted 7 months, 1 week ago // Permalink

    Does WP automatically know what category is which or which post I want the style on or do I need to add something to the individual posts (e.g. an id )?

  22. Posted 7 months, 1 week ago // Permalink

    @jj - the code, once inserted, always outputs the added classes to the BODY tag. However that should be no issue to you, as nothing happens with that unless you write CSS declarations to take advantage of it. And no, it will sit fine alongside flash stuff.

    @j boulanger - WP does know what categories are associated with each post. My plugin fetches this information and turns it into classes in the BODY tag. You don’t need to add an ID or anything, that’s all taken care of between WP and my plugin.

    - Alister

  23. Posted 6 months, 2 weeks ago // Permalink

    world class plugin.I think you read my mind about CSS classification in WP.Great keep it up

  24. Posted 6 months ago // Permalink

    Awesome plugin, Alister! I just came across this plugin through someone else and I can see the possibilities are endless to give a blog it’s unique look!

  25. ovidiu
    Posted 6 months ago // Permalink

    hello Alister,

    any chance you could update your plugin so it detects author pages too? something like: http://www.alistercameron.com/author/alister ?

  26. Posted 5 months, 4 weeks ago // Permalink

    I love this plugin! It’s very powerful!

    I have a question/problem that I was hoping you could solve, however.

    I’m trying to get categories to appear in the body class for single posts (as you have on this very page) but I can’t get it to work. Any ideas?

    Thanks!

  27. Posted 2 months, 4 weeks ago // Permalink

    I’ve been playing with a blog redesign lately, and got thinking about this..

    Ended up sharing it with a few bloggers around the place.

  28. Posted 1 month, 1 week ago // Permalink

    This is a great plugin!

    I’ve been using a class on my body tag for the last few years on static sites mainly for navigation effects, banner and headings…stuff like that. But now you’ve inspired me to get it into my blogs.

    I have a new theme all ready to go, I’ll try to get this in there so I can release it with some customization power.

    Thanks for this Alister.

40 Trackbacks/Pingbacks

  1. adding class to body…

    new found wordpress plugin: ClassyBody. very powerful. and damn smart.
    tags: 

    ……

  2. [...] Wordpress Plugin: ClassyBody Add a class to the body tag of your Wordpress blog depending on various parameters such as single page, page, post, category etc. (tags: wp-plugins plugin wordpress css webdesign) [...]

  3. [...] Alister’s Blog [...]

  4. links from Technorati Wordpress Plugin: ClassyBody | Alister Cameron, Blog Consultant ページのBodyタグに異なるクラスをつける

  5. links from TechnoratiWP Plugin: ClassyBody WP Plugin: ClassyBody Add a class to the body tag of your Wordpress blog depending on various parameters such as single page, page, post, category etc. In other words, it gives you the power to control the look and feel of your blog using CSS but dependent on the condition

  6. links from Technorati Wordpress Plugin: ClassyBody | Alister Cameron, Blog Consultant ClassyBody adds contextually-relevant classes to your body tag. これで完璧?del.icio.usとの付き合い方 | caramel*vanillaクレジットカード勧誘スタッフの裏話運用 : Windows XPで始める無線LAN

  7. links from Technorati ClassyBody

  8. [...] ClassyBody Add a class to the body tag of a Wordpress blog depending on various parameters such as single page, page, post, category etc. You could make your single pages look different or a single post have a festive theme with modification of the CSS. [via wltc] (tags: wordpress) [...]

  9. [...] plan to exploit my ClassyBody plugin to add spice and variety to different sections/categories of the [...]

  10. [...] same thinking is behind my first Wordpress plugin, my Wordpress mod_rewrite contributions, and my Habari logo idea… do you get [...]

  11. links from Technorati Hmm, that would be a little bit like what Alister wrote about Knuttz recently. I am not sure of the easiest way to leverage it.. maybe an invisible category “hot”. It might also have some use combined with Alister’s Classy Body Plugin so that not only can you have a different look for a category, almost like a seperate blog, but also display the top posts in that section. Note:- I haven’t tested these plugins yet

  12. [...] have updated my ClassyBody Wordpress plugin to v1.1 with the addition of ad-hoc custom CSS [...]

  13. [...] ClassyBody adds contextually intelligent CSS classes to your BODY tag, giving the more high-powered designers out there much greater control of the CSS of a given Wordpress page. [...]

  14. [...] ClassyBody añade nuevas funciones para la gestión de estilos para diseñadores de plantillas en WordPress. [...]

  15. links from Technorati Wordpress Plugin: ClassyBody » Alister Cameron, Blog Consultant

  16. Kramer auto Pingback[...] Wordpress Plugin: ClassyBody | Alister Cameron, Blog Consultant [...]

  17. Kramer auto Pingback[...] Are you looking to control the look and feel of your blog using CSS?. Alister Cameron has released a plugin “ClassyBody” for WordPress. You can very safely and easily install “ClassyBody” without any fear of messing your existing design. You can find the complete details at Alister Cameron`s blog [...]

  18. [...] ClassyBody adds contextually intelligent CSS classes to your BODY tag, giving the more high-powered designers out there much greater control of the CSS of a given Wordpress page. [...]

  19. Kramer auto Pingback[...] Classy Body CSS Plugins My Comic Browser PHP Advanced Transfer Manager Random Header Images Simple Viewer Wordpress Review plugin Return [...]

  20. Kramer auto Pingback[...] Wordpress Plugin: ClassyBody | Alister Cameron, Blog Consultant [...]

  21. links from TechnoratiComment Analysis contains a suite of functions which examine the comments on your blog. Category Overload provides an alternate administrative interface for managing categories in WordPress. Docs and download. ClassyBody adds contextually intelligent CSS classes to your BODY tag, giving the more high-powered designers out there much greater control of the CSS of a given Wordpress page. FirstRSS and SideRSS will let you insert an RSS feed into a template with only one

  22. Kramer auto Pingback[...] Wordpress Plugin: ClassyBody | Alister Cameron, Blog Consultant 各ページのbody要素にクラスを付与するWordPressプラグイン。ページ毎のデザインがやりやすくなる。 (tags: wordpress plugin) [...]

  23. Kramer auto Pingback[...] ClassyBody WordPress Plugin adds CSS styles to your WordPress Theme’s HTML body tag for each type of page view you may use on your WordPress blog. For instance, if you would like your category pages to look a specific way when generated, you can style a “look” for the page from the category or cat-ID# CSS style. [...]

  24. Kramer auto Pingback[...] Wordpress Plugin: ClassyBody | Alister Cameron, Blog Consultant [...]

  25. [...] it generates exactly the kind of HTML that a CSS junkie like me drools over. You may recall my ClassyBody plugin of a few months ago. This plugin was trying to do in one tag (the BODY tag) what Sandbox does right [...]

  26. Kramer auto Pingback[...] I’m trying not to have to run parallel installs of WP if I don’t have to. Oli on May. 14, 2007 Have a look at this. BinaryMoon on May. 14, 2007 I would stick the dog based stuff in a separate category. Then install this plugin [...]

  27. Kramer auto Pingback[...] Browser blog css wordpress design themes Agregado hace >30 días de mcdave, 6 Usuarios guardarWordpress Plugin: ClassyBody » Alister Cameron, Blog Co … css wordpress design plugin webdev plugins [»] Agregado hace >30 días de dubo, 1 Usuario [...]

  28. Kramer auto Pingback[...] Wordpress Plugin: ClassyBody » Alister Cameron, Blog Consultant About Preview [...]

  29. [...] As I said, I’ll ask Ben to weigh in below in the first comment section with his thoughts. You can find out more about Alister at his site here and the Classy body plugin Alister refers to in the clip is here. [...]

  30. links from Technoratieasy to add Most popular posts by month, all time, categories, etc. WordPress Stats - Tracks views, pageviews, referrers and clicks. It shows what people clicked on as well as search terms. You need a WordPress.com API key to activate this. StylingClassyBody- A very powerful plugin that hooks simple CSS classes to the body tag. You can modify the look and feel of every part of your site with these hooks very easily. File Icons - Adds icons to links via CSS.

  31. [...] Wordpress Plugin: ClassyBody (tags: wordpress plugin css) [...]

  32. [...] tela gerada pelo Wordpress e, assim, facilitar a criação do CSS. O You Are Here é baseado no plugin ClassyBody de Alister Cameron. Porém, o plugin dele criava as identificações baseado no ID, e isso muitos vezes gerava alguns [...]

  33. Kramer auto Pingback[...] I’m using the Classy Body plugin for that: http://www.alistercameron.com/2007/01/04/wordpress-plugin-classybody/ [...]

  34. links from TechnoratiLayout e CSSClassy BodyEm todos os meus sites estáticos gosto de usar identificadores e classes na tag body. Isto permite mais flexibilidade de layout com menos código e customização do template. O Classy Body usa apenas classes compostas. De qualquer forma, é um sonho

  35. [...] Classy Body [...]

  36. links from Technoratit have passion and purpose, greater productivity won’t help you! - 14,132 Views The 100% guaranteed way to get a front page story on Digg! - 12,811 Views How to grow your blog by over 2000 per cent in one month! - 9,196 ViewsWordpress Plugin: ClassyBody- 8,229 Views

  37. Kramer auto Pingback[...] He does some funky things with Wordpress themes and CSS too - check out: http://www.alistercameron.com/2007/01/04/wordpress-plugin-classybody/ [...]

  38. Kramer auto Pingback[...] I suggest you try the ClassyBody plugin. [...]

  39. links from Technoratiview blog

  40. links from TechnoratiWordpress Plugin: ClassyBody

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*
  • A Few Words About Me

    If you haven't worked it out yet, I'm passionate about blogging! I build blogs, I optimize and market blogs, I coach bloggers, and in the gaps I blog about blogging. Phew!

    I am a capable designer, programmer, marketer, writer, trainer/educator and strategist, obsessing over this internet thing since 1995.

    If you're serious about blogging, I would suggest taking some time to read my blog. Then, if you want more of me, get in touch...

    Contact details »

  • Look Who's Been Here!

  • My Posts in Your In-box!

    Enter your email address here for instant updates in your inbox, whenever I post something new.
    Your email address is in safe hands. Relax!
© Copyright 2008 Alister Cameron. All Rights Reserved Theme // Sitemap // RSS