WordPress Body Class 101: Tips and Tricks for Theme Designers

By | March 25, 2021

Are you an aspiring WordPress theme designer looking for new ways to use CSS into your themes?

Luckily, WordPress automatically adds CSS classes that you can utilize in your themes. Several of these CSS classes are automatically added to the <body> section of every page on a WordPress site.

In this article, we will explain the WordPress body class with tips and tricks for aspiring theme designers to utilize them in their projects.

Using WordPress body class for theme development
Here is a quick overview of what you’ll learn in this article.

What is WordPress Body Class?

Body class (body_class) is a WordPress function that allows you to assign CSS classes to the body element.

The HTML body tag normally begins in a theme’s header.php file, which loads on every page. This allows you to dynamically figure out which page a user is viewing and then add the CSS classes accordingly.

Normally most starter themes and frameworks already include the body class function inside the HTML body tag. However, if your theme does not have it, then you can add it by modifying the body tag like this:

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

Depending on the type of page being displayed, WordPress automatically adds the appropriate classes.

For example, if you are on an archive page, WordPress will automatically add archive class to the body element. It does that for just about every page.

Related: See how WordPress works behind the scenes (infographic)

Here are some examples of common classes that WordPress might add, depending on which page is being displayed:

.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) {}

As you can see, by having such a powerful resource at hand, you can entirely customize your WordPress page by using just CSS. You can customize specific author profile pages, date-based archives, etc.

That being said, now let’s take a look at how and when would you use the body class.

When to use The WordPress Body Class

First, you need to make sure that your theme’s body element contains the body class function as shown above. If it does, then it will automatically include all the WordPress generated CSS classes mentioned above.

After that, you will also be able to add your own custom CSS classes to the body element. You can add these classes whenever you need them.

For example, if you want to change the appearance of articles by a specific author filed under a specific category.

How to Add Custom Body Classes

WordPress has a filter that you can utilize to add custom body classes when needed. We will show you how to add a body class using the filter before showing you the specific use case scenario just so everyone can be on the same page.

Because body classes are theme specific, you would need to add the following code to your theme’s functions.php file.

function my_class_names($classes) {
	// add 'class-name' to the $classes array
	$classes[] = 'wpb-class';
	// return the $classes array
	return $classes;
}

//Now add test class to the filter
add_filter('body_class','my_class_names');

The above code will add a class “wpb-class” to the body tag on every page on your website. That’s not so bad, right?

Now you can utilize this CSS class in your theme’s stylesheet directly. If you are working on your own website, then you can also add the CSS using the custom CSS feature in theme customizer.

Adding custom CSS in theme customizer

Adding Body Class Using a WordPress Plugin

If you are not working on a client project and don’t want to write code, then this method would be easier for you.

The first thing you need to do is install and activate the Custom Body Class plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Upon activation, you need to visit Settings » Custom Body Class page. From here you can configure plugin settings.

Custom Body Class settings

You can select post types where you want to enable body class feature and who can access it. Don’t forget to click on the save changes button to store your settings.

Next, you can head over to edit any post or page on your WordPress site. On the post edit screen, you will find a new meta box in the right column labeled ‘Post Classes’.

Adding body classes to a post in WordPress

Click to add your custom CSS classes. You can add multiple classes separated by a space.

Once you are done, you can simply save or publish your post. The plugin will now add your custom CSS classes to the body class for that particular post or page.

Using Conditional Tags with The Body Class

The real power of the body_class function comes when it is used with the conditional tags.

These conditional tags are true or false data types that check if a condition is true or false in WordPress. For example, the conditional tag is_home checks if the page currently displayed is the homepage or not.

This allows theme developers to check if a condition is true or false before adding a custom CSS class to the body_class function.

Let’s take a look at some examples of using conditional tags to add custom classes to the body class.

Let’s say you want to style your homepage differently for logged in users with the author user role. While WordPress automatically generates a .home and .logged-in class, it does not detect the user role or add it as a class.

Now, this is a scenario where you can use the conditional tags with some custom code to dynamically add a custom class to the body class.

To achieve this you will add the following code to your theme’s functions.php file.

function wpb_loggedin_user_role_class($classes) { 

// let's check if it is homepage
if ( is_home() ) {

// Now let's check if the logged in user has author user role.  
$user = wp_get_current_user();
if ( in_array( 'author', (array) $user->roles ) ) {
    //The user has the "author" role
    // Add user role to the body class
    $classes[] = 'author';
    // Return the classes array
    return $classes;      
} 
} else { 
// if it is not homepage, then just return default classes
return $classes; 
}
} 

add_filter('body_class', 'wpb_loggedin_user_role_class');

Now, let’s take a look at another useful example. This time we are going to check if the page displayed is a preview of a WordPress draft.

To do that we will use the conditional tag is_preview and then add our custom CSS class.

function add_preview_class($classes) { 
if ( is_preview() )  {
$classes[] = 'preview-mode';
return $classes;
}
return $classes; 
}
add_filter('body_class','add_preview_class');

Now, we will add the following CSS to our theme’s stylesheet to utilize the new custom CSS class we just added.

.preview-mode .site-header:before { 
content:'preview mode';
color:#FFF;
background-color:#ff0000;
}

This is how it looked on our demo site:

Custom preview mode CSS class added to the body class

You may want to check out the full list of conditional tags that you can use in WordPress. This will give you a handy set of ready to use tags for your code.

Other Examples of Dynamically Adding Custom Body Classes

Apart from conditional tags, you can also use other techniques to fetch information from the WordPress database and create custom CSS classes for the body class.

Adding category names to the body class of a single post page

Let’s say you want to customize the appearance of single posts based on the category they are filed in. You can use the body class to achieve this

First, you need to add category names as CSS class on single post pages. To do that, add the following code to your theme’s functions.php file:

// add category nicenames in body class
function category_id_class($classes) {
    global $post;
    foreach((get_the_category($post->ID)) as $category)
        $classes[] = $category->category_nicename;
    return $classes;
}
 
add_filter('body_class', 'category_id_class');

The code above will add the category class in your body class for single post pages. You can then use CSS classes to style it as you wish.

Adding page slug to the body class

Paste the following code in your theme’s functions.php file:

//Page Slug Body Class
function add_slug_body_class( $classes ) {
global $post;
if ( isset( $post ) ) {
$classes[] = $post->post_type . '-' . $post->post_name;
}
return $classes;
}
add_filter( 'body_class', 'add_slug_body_class' );

Browser Detection and Browser Specific Body Classes

Sometimes you may come across issues where your theme may need additional CSS for a particular browser.

Now the good news is that WordPress automatically detects browser upon loading and then temporary stores this information as a global variable.

You just need to check if WordPress detected a specific browser and then add it as a custom CSS class.

Simply, copy and paste the following code in your theme’s functions.php file:


function wpb_browser_body_class($classes) { 
	global $is_iphone, $is_chrome, $is_safari, $is_NS4, $is_opera, $is_macIE, $is_winIE, $is_gecko, $is_lynx, $is_IE, $is_edge;

if ($is_iphone)    $classes[] ='iphone-safari';
elseif ($is_chrome)    $classes[] ='google-chrome';
elseif ($is_safari)    $classes[] ='safari';
elseif ($is_NS4)    $classes[] ='netscape';
elseif ($is_opera)    $classes[] ='opera';
elseif ($is_macIE)    $classes[] ='mac-ie';
elseif ($is_winIE)    $classes[] ='windows-ie';
elseif ($is_gecko)    $classes[] ='firefox';
elseif ($is_lynx)    $classes[] ='lynx';
elseif ($is_IE)      $classes[] ='internet-explorer';
elseif ($is_edge)    $classes[] ='ms-edge';
else $classes[] = 'unknown';
	
return $classes;
}
add_filter('body_class','wpb_browser_body_class');

You can then use classes like:

.ms-edge .navigation {some item goes here}

If it is a small padding or margin issue, then this is a fairly easy way of fixing it.

There are definitely many more scenarios where using the body_class function can save you from writing lengthy lines of code. For example, if you are using a theme framework like Genesis, then you can use it to add custom classes in your child theme.

You can use the body_class function to add CSS classes for full-width page layouts, sidebar content, header and footers, etc.

We hope this article helped you learn how to use the WordPress body class in your themes. You may also want to see our article on how to style each WordPress post differently, and our comparison of best WordPress page builder plugins.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

The post WordPress Body Class 101: Tips and Tricks for Theme Designers appeared first on WPBeginner.

Leave a Reply

Your email address will not be published. Required fields are marked *