Notice how the different sections of my website have a different background color? Well, this isn’t a particularly challenging piece of code to implement but since I launched my new site a few weeks ago I’ve had a few of emails and tweets asking how it was done.
Setting up a friendly ‘body_class()’ in WordPress
By default most WordPress themes will add a CSS class to your sites <body> element that includes the post type, page/post ID and any template you may be using. It looks something like this:
If your theme doesn’t have a body_class() set up you can add your own using the following bit of code:
This CSS class allows you to individually style pages/posts by referencing the values in this class from your themes stylesheet.
But the post/page ID is a little difficult to remember, it could also change if you do a major edit, so how about using the title instead?
Check out how my site loads it’s body_class() for my WordPress services page:
Note the addition of ‘page-wordpress’.
And here is the code snippet that makes that happen (add to your functions.php file):
This code gets the page type: ‘$post->post_type‘ (in this case ‘page’) and the page name: ‘$post->post_name‘ (taken from the slug) and adds then to the body_cass() – for example an ‘About Kimb‘ page would return ‘page-about-kimb‘.
Changing the WordPress page background color with CSS
And now the easy part, choosing your colours – here’s a snippet from my stylesheet:
Done! Now I can reference any new page titles using a more friendly and memorable body_class().
Learn more about the WordPress body_class()
I’ve used the body_class() feature since it was introduced in WordPress 2.8, it’s really useful for pages with logged-in users and advanced homepage layouts. Before this was introduced developers would have to cobble together custom elements using conditional tags and other nasty complex hacks.
Some useful example classes which WordPress adds are:
- page-parent
- page-template page-template-{directory}{filename}_php
- search-results
- error404
- logged-in
- author-user_nicename
- single-{posttype}
- home page