WPBeginner

Beginner's Guide for WordPress

  • Blog
    • Beginners Guide
    • News
    • Opinion
    • Showcase
    • Themes
    • Tutorials
    • WordPress Plugins
  • Start Here
    • How to Start a Blog
    • Create a Website
    • Start an Online Store
    • Best Website Builder
    • Email Marketing
    • WordPress Hosting
    • Business Name Ideas
  • Deals
    • Bluehost Coupon
    • SiteGround Coupon
    • WP Engine Coupon
    • HostGator Coupon
    • Domain.com Coupon
    • Constant Contact
    • View All Deals »
  • Glossary
  • Videos
  • Products
X
☰
Beginner's Guide for WordPress / Start your WordPress Blog in minutes
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

WPBeginner» Blog» Themes» WordPress Body Class 101: Tips and Tricks for Theme Designers

WordPress Body Class 101: Tips and Tricks for Theme Designers

Last updated on March 25th, 2021 by Editorial Staff
229 Shares
Share
Tweet
Share
Pin
Free WordPress Video Tutorials on YouTube by WPBeginner
WordPress Body Class 101: Tips and Tricks for Theme Designers

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?
  • When to use the body class
  • How to add custom body classes
  • How to add body class using a plugin
  • Using conditional tags to add custom body classes
  • More examples of dynamically adding custom body classes
  • Detecting user browser and adding browser specific body class

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.

229 Shares
Share
Tweet
Share
Pin
Popular on WPBeginner Right Now!
  • How to Start Your Own Podcast (Step by Step)

    How to Start Your Own Podcast (Step by Step)

  • Checklist

    Checklist: 15 Things You MUST DO Before Changing WordPress Themes

  • How to Properly Move Your Blog from WordPress.com to WordPress.org

  • Google Analytics in WordPress

    How to Install Google Analytics in WordPress for Beginners

About the Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. Trusted by over 1.3 million readers worldwide.

The Ultimate WordPress Toolkit

13 Comments

Leave a Reply
  1. jenny says:
    Sep 9, 2015 at 7:15 am

    plsss give me example outwitting a crocodile theme plsssssssss

    Reply
  2. Corrinda says:
    May 10, 2013 at 11:48 am

    Thank you after reading a number of articles regarding the body-class this is the one the finally sunk in.

    Got it working on individual pages and on category pages this is great. The use cases are what made the difference for me.

    Reply
    • Editorial Staff says:
      May 12, 2013 at 8:06 am

      Sweet. Glad to be able to help.

      Reply
  3. Yolanda says:
    Mar 27, 2013 at 9:58 am

    Great tips! I’m trying to figure out how to add the menu class (the one you can enter in the admin) to body_class:

    [pre]
    /** Add nav menu css class to body class */
    function add_nav_menu_css( $classes ) {
    $classes[] = ‘menu-class-from-admin’;
    return $classes;
    }
    add_filter( ‘body_class’, ‘add_nav_menu_css’ );
    [/pre]

    Reply
  4. Seth Burleigh says:
    Jan 9, 2013 at 12:36 am

    Great tips. I”m trying to do this, and when inserting “page-template page-template-(template file name)” into my header file such that I have:

    <body >

    And I then modify my CSS to include: .page-template-home_corechella

    I am left with a completely blank page. Nothing. What am I doing wrong? Thanks!

    Reply
    • Editorial Staff says:
      Jan 10, 2013 at 11:30 am

      The page-templates are added in the homepage automatically as long as you have the body_class tags. Would have to see the file to see what you are doing wrong. Use a third party service like pastebin, and then paste the link here.

      Reply
      • Seth says:
        Jan 10, 2013 at 6:34 pm

        Ok, thank you very much!

        I’ve changed the approach slightly since my post (now using instead of page template), but a similar problem is happening – the correct body CSS (body.corechella) is not showing. The original body class is taking priority.

        Corechella Page template (http://dev.corebaby.org/corechella-home/) – http://pastebin.com/embed_js.php?i=8L6rhESr
        Corechella header.php file – http://pastebin.com/embed_js.php?i=n2Sn4jUJ
        CSS (the new body class is at the very bottom) – http://pastebin.com/embed_js.php?i=4U6d09cQ”

        Seth

        Reply
        • Editorial Staff says:
          Jan 16, 2013 at 3:12 pm

          In your header.php, you have to keep the body class like this:

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

          In your CSS, just use .corchella instead of body.corchella

  5. Michael says:
    Nov 5, 2012 at 5:07 am

    Great write up, thanks

    Reply
    • Editorial Staff says:
      Nov 6, 2012 at 10:12 am

      Glad you found it helpful :)

      Reply
  6. Rasha says:
    Oct 16, 2012 at 9:54 am

    i have news page that get posts using category.php , i want to give it specific class so i can make the content wide and without the sidebar , how i can do that ?

    Reply
  7. Vajrasar says:
    Oct 12, 2012 at 2:14 am

    Indeed a good writeup and very informative. Just a question – For example if I add Browser Specific Body Class today and after few days I need to apply Page Class in Body Slug. Then will the settings/css that I did with Browser Specific Body class will get ruined or not?

    Reply
    • Editorial Staff says:
      Oct 12, 2012 at 9:24 am

      No it will not get ruined. It can be overridden depending on how your CSS is written.

      Reply

Leave a Reply Cancel reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Over 1,320,000+ Readers

Get fresh content from WPBeginner

Featured WordPress Plugin
Smash Balloon
Smash Balloon
Add Custom Social Media Feeds in WordPress. Learn More »
How to Start a Blog How to Start a Blog
I need help with ...
Starting a
Blog
WordPress
Performance
WordPress
Security
WordPress
SEO
WordPress
Errors
Building an
Online Store
Useful WordPress Guides
    • 7 Best WordPress Backup Plugins Compared (Pros and Cons)
    • How to Fix the Error Establishing a Database Connection in WordPress
    • Why You Need a CDN for your WordPress Blog? [Infographic]
    • 30 Legit Ways to Make Money Online Blogging with WordPress
    • Self Hosted WordPress.org vs. Free WordPress.com [Infograph]
    • Free Recording: WordPress Workshop for Beginners
    • 24 Must Have WordPress Plugins for Business Websites
    • How to Properly Move Your Blog from WordPress.com to WordPress.org
    • 5 Best Contact Form Plugins for WordPress Compared
    • Which is the Best WordPress Popup Plugin? (Comparison)
    • Best WooCommerce Hosting in 2021 (Comparison)
    • How to Fix the Internal Server Error in WordPress
    • How to Install WordPress - Complete WordPress Installation Tutorial
    • Why You Should Start Building an Email List Right Away
    • How to Properly Move WordPress to a New Domain Without Losing SEO
    • How to Choose the Best WordPress Hosting for Your Website
    • How to Choose the Best Blogging Platform (Comparison)
    • WordPress Tutorials - 200+ Step by Step WordPress Tutorials
    • 5 Best WordPress Ecommerce Plugins Compared
    • 5 Best WordPress Membership Plugins (Compared)
    • 7 Best Email Marketing Services for Small Business (2021)
    • How to Choose the Best Domain Registrar (Compared)
    • The Truth About Shared WordPress Web Hosting
    • When Do You Really Need Managed WordPress Hosting?
    • 5 Best Drag and Drop WordPress Page Builders Compared
    • How to Switch from Blogger to WordPress without Losing Google Rankings
    • How to Properly Switch From Wix to WordPress (Step by Step)
    • How to Properly Move from Weebly to WordPress (Step by Step)
    • Do You Really Need a VPS? Best WordPress VPS Hosting Compared
    • How to Properly Move from Squarespace to WordPress
    • How to Register a Domain Name (+ tip to get it for FREE)
    • HostGator Review - An Honest Look at Speed & Uptime (2021)
    • SiteGround Reviews from 4464 Users & Our Experts (2021)
    • Bluehost Review from Real Users + Performance Stats (2021)
    • How Much Does It Really Cost to Build a WordPress Website?
    • How to Create an Email Newsletter the RIGHT WAY (Step by Step)
    • Free Business Name Generator (A.I Powered)
    • How to Create a Free Business Email Address in 5 Minutes (Step by Step)
    • How to Install Google Analytics in WordPress for Beginners
    • How to Move WordPress to a New Host or Server With No Downtime
    • Why is WordPress Free? What are the Costs? What is the Catch?
    • How to Make a Website in 2021 – Step by Step Guide
Deals & Coupons (view all)
Elegant Themes
Elegant Themes Deal
Get the Divi theme with 194+ template packs from Elegant Themes for only $89. Extra, Bloom, and Monarch included free!
TeslaThemes
TeslaThemes Coupon
Get 20% off on TeslaThemes large collection of premium WordPress themes.
Featured In
About WPBeginner®

WPBeginner is a free WordPress resource site for Beginners. WPBeginner was founded in July 2009 by Syed Balkhi. The main goal of this site is to provide quality tips, tricks, hacks, and other WordPress resources that allows WordPress beginners to improve their site(s).

Join our team: We are Hiring!

Site Links
  • About Us
  • Contact Us
  • FTC Disclosure
  • Privacy Policy
  • Terms of Service
  • Free Blog Setup
  • Free Business Tools
  • Growth Fund
Our Sites
  • OptinMonster
  • MonsterInsights
  • WPForms
  • SeedProd
  • Nameboy
  • RafflePress
  • Smash Balloon
  • AIOSEO

Copyright © 2009 - 2021 WPBeginner LLC. All Rights Reserved. WPBeginner® is a registered trademark.

Managed by Awesome Motive | WordPress hosting by SiteGround | WordPress Security by Sucuri.