WordPress Body Class body_class() Function and extension

The WordPress body class function body_class() works from WordPress 2.8 version onwards. This function gives the body element different classes and can be added, typically, in the header.php’s HTML body tag. This gives you the possibility to use it effectively with CSS.

<body <?php body_class(); ?>>

What body_class() Generates

The body_class() function is quite similar to post_class() function that was introduced in WordPress 2.7. The only differences are the classes it generates. The body_class() function will generate the classes mostly based on where your viewer is on your site.

Following in example of the class that is generated through body_class() function when your visitor come to your site
In Hompage: <body class="home blog">
In Interviews Category: <body class="archive category category-interviews">
In About us Page: <body class="page page-id-2">
In Post: <body class="single postid-36">
In 404 Error Page: <body class="error404">

But the then it will add extra class logged-in if your visitors are logged in your site.

To add to more: The body_class() may include one or more of the following values for the class attribute.

  • 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)

You can also extend the body call with the use of Hook in your Function.php file in your theme. The following in the example that you can use it is function.php file
add_filter('body_class','my_body_classes');
function my_body_classes($classes) {
if (is_single()) {
if (in_category('News')) {
$classes[] = 'category-news';
} else if (in_category('Travel &amp; Nepal')) {
$classes[] = 'category-travel-nepal';
} else if (in_category('Interviews')) {
$classes[] = 'category-interviews';
} else if (in_category('How To')) {
$classes[] = 'category-how-to';
}
}
return $classes;
}

What I did in the above hook is that I forced body_class() function to add the category name in which the post belongs while viewing the post. Now, when you will view your post you will see the category name in which it belongs: Following are the example:
In Post which belongs to News category: <body class="single postid-36 category-news">

One Reply to “WordPress Body Class body_class() Function and extension”