How to Use the Body Class Tag to Apply Custom Styles to WordPress Pages

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:

{code type=php}

Now when you view the source of your page, you should see a new output for the body tag, similar to this:

{code type=html}

If you’re viewing a category archive page, it may look similar to this:
{code type=html}

Now that you have this output you can use the new CSS classes to customize the page, ie. :
{code type=css} {
width: 980px;

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.

  • rtl
  • home
  • blog
  • archive
  • date
  • search
  • paged
  • attachment
  • error404
  • single postid-(id)
  • attachmentid-(id)
  • attachment-(mime-type)
  • author
  • author-(user_nicename)
  • category
  • category-(slug)
  • tag
  • tag-(slug)
  • page-parent
  • page-child parent-pageid-(id)
  • page-template page-template-(template file name)
  • search-results
  • search-no-results
  • logged-in
  • 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.