Add body_class to body tag in WordPress

One of the great things about WordPress is the theme. It helps to make sure that all of you pages and posts are uniform, providing a good experience for your visitors and working with you brand to keep things consistent. But sometimes you need to do something on one specific page – change the color of headers on one page or on all posts within a specific category. While you could probably write some complicated if/then statements and make custom page templates and all that jazz, there is usually an easier way to accomplish this – add the body_class() function to the body tag in your theme.

So, what is this magical function? Well, I’m glad you asked. From the WordPress Codex, “This function gives the body  element different classes and can be added, typically, in the header.php’s HTML body tag.” Some of the things that it adds to the body tage are the page or post slug, page or post id, which page template is being used, and other identifiers.

How do you use it? It’s pretty simple.  Without the function, the body tag usually looks something like this:

[sourcecode language=”php”]
< body >
[/sourcecode]

(I added a space between the opening < and body so the browser doesn’t try to render the code. Your’s should not have a space there or it won’t work.)

With the function, it should look like:

[sourcecode language=”php”]
< body >
[/sourcecode]

And if you view the source code of your page after adding this, you should see something like this:

[sourcecode language=”php”]
< body class="home page page-id-2 page-template-default logged-in admin-bar customize-support">
[/sourcecode]

Leave a Comment