How to Use the Body Class Tag to Apply Custom Styles to WordPress Pages
WordPress introduced the body_class() template tag in 2.8 to help theme authors style more effectively with CSS. You may not have needed it before, but the body_class template tag is so incredibly handy and versatile that it’s worth knowing how to use.
Why the body_class() tag is needed
In WordPress there is generally one body tag in your header.php file and numerous other templates that share the same header. This makes it tricky to add unique classes to the body tag based on the user’s location in the site. With static html files you can simply add in a body class depending on the needs of your page. However, with WordPress you will need a little help. The first time I needed to use it was in working on a site that required different background pages for each category archive page. The body_class() template tag saved the day.
How to use the body_class() template tag
Adding body_class() to your theme is very simple. Open your header.php file and replace the < body > tag with:
Now when you view the source of your page, you should see a new output for the body tag, similar to this:
If you’re viewing a category archive page, it may look similar to this:
Now that you have this output you can use the new CSS classes to customize the page, ie. :
Many times these new outputs are enough to work with for you to create custom backgrounds, target specific browsers, or change the style based on if a user is logged in or not.
How to further customize the body_class() template tag
An extensive list of classes is available for you to use to fine-tune your body tag. Select one or more and then add them to the tag.
- single postid-(id)
- page-child parent-pageid-(id)
- page-template page-template-(template file name)
- paged-(page number)
- single-paged-(page number)
- page-paged-(page number)
- category-paged-(page number)
- tag-paged-(page number)
- date-paged-(page number)
- author-paged-(page number)
- search-paged-(page number)
The body_class() template tag will save you from having to use lines and lines of conditional statements or any of the other complicated methods you used to use to make the body tag accessible by CSS. Once you harness the power of the body_class() tag, an unlimited number of customizations will be available to you.Tags: