How To Add a Custom Class To The Body Tag In WordPress

Home » Blog » WordPress Development » How To Add a Custom Class To The Body Tag In WordPress

Do you want to add a custom CSS class to the body tag? You can easily do so by adding a filter function to the body_class filter. This will let you modify the list of classes added to the body tag.

Add this code to your theme’s functions.php file, or add it to a custom plugin:

function add_custom_body_class( $classes ) {

    // Add a class if this is the homepage.
    if ( is_home() ) {
        $classes[] = 'homepage';
    }

    // Add a class if this page is not the homepage.
    if ( !is_home() ) {
        $classes[] = 'not-homepage';
    }

    // Add class is an administrator.
    if ( current_user_can('administrator') ) {
        $classes[] = 'administrator-user';
    }

    // Add a class to all posts of the recipes posts type.
    if ( is_singular('recipes') ) {
        $classes[] = 'recipe-post';
    }

    // Add a custom class to the body tag unconditionally.
    $classes[] = 'my-custom-body-class';

    return $classes;
}
add_filter( 'body_class', 'add_custom_body_class' );

The above code adds a filter function to the body_class filter. Our filter function add_custom_body_class will receive an array of classes that will be added to the body tag. The above code adds a new custom class to this array depending on what page the user is currently at.

I have added a couple of example conditions in the above code that you can edit. If you want to add a class to the body tag unconditionally, replace my-custom-body-class at the end of the code with your desired class. This class will be added to all the body tags of all the pages on your website.

For this code to work, your theme needs to call the body_class function on the body tag. If your theme doesn’t already do so, add it yourself:

<body <?php body_class() ?>>

Just replace the opening body tag in your theme’s header.php file with the above code if it doesn’t already look like this.

Leave a Reply

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

Register an account to save your snippets or go Pro to get more features.