A better body_class for WordPress 2.8
by Moises Kirsch
WordPress 2.8 introduced a very useful new tag called body_class which normally will be used like this:
<body <?php body_class(); ?>>
The only problem is that it uses the ID’s instead of the page slugs making it a little harder to use the classes on your CSS (or Javascript).
A very easy way to fix this is to call the function with an argument like this:
<body <?php body_class( str_ireplace( '/', ' ', get_page_uri($post->ID) ) ); ?>>
What we are doing is adding the permalink structure as classes. That way you could target all the pages with the same parent, from the same category or so on without needing to know the ID. This is great if you are developing a theme and there is no way for you to know the ID of certain category or page.
Comments
[...] Original post: A better body_class for WordPress 2.8 | WP Kode [...]
Perfect. Thank you.
I was excited to see the new functionality in 2.8 and then quickly deflated to see we were tied to IDs. This saves a ton of work.
Best,
Clayton
[...] Here is a little update to my better body_class code: [...]
Exactly what I needed. Nice one!
How would I go about adding the posts category along with the posts name or is this possible?
For example, I have a page named “work” that lists posts under the category work – http://domain.com/work). When you click on one of the posts to read the whole article the the url for the article is http://domain.com/work/articleName. I would like any post in the category work to have a body class that includes “work”.
Marlowe,
This should do it.
But I did enhance this function a lot more… you can see it here:
http://wpkode.com/2009/07/an-even-better-body_class-for-wordpress/