Add an additional Body Class to WordPress by using the Post Slug

One of the real useful things I’ve come across with WordPress is the body_class() method. This adds several classes to the body element of your HTML. The output looks something like below:

body-class

Why is this so great? Now you can style your pages very efficiently because you’re able to select from the template you’re using, the post type, when user is logged in – even to the post Id.

An example of what I mean is say – you want all the H1 tags styled differently only for post ID “4396”. Now in you CSS file you can add a rule like below:

This will effectively target only that post’s h1 tags. Pretty useful right?

Add a Post slug to the Body Class

Now let’s take it a step further. If you’re like me who develop themes all day – you probably have a local server set up. Now, the problem with that is – you may not have your WordPress databases the same as the production site. So your post ids may not be the same!

The solution: use the post slug as an additional class. For example, you want to style the “About us” page’s H1 tags differently than the rest of the pages. So instead of relying on the default body_class()’s post id, simply add the code below to your functions.php file:

Then, in your header.php file (or where you have your opening body tag is), add the call to the body_class():

The output will be something like below:

body-class-2

Now you can code your CSS like so:

Conclusion

Pretty neat right? Adding a body class that is based on your post slug is not only very helpful, but also very semantic. The upside of using the slug is its always lowercase and no spaces (unless you change them when you create a post). But then – you can deal with that accordingly. Tell me your comments below.

1 Comments

  1. did not work for me… get a blank page when load the site (which means there’s a PHP error somewhere……)

    this code has to be put in functions.php inside theme folder yes? (why are there two functions.php in WP download… not very practical….:-( )

    thank you……

    Reply

Leave a Comment.