Using WordPress ‘body_class()’ PHP function

The body_class() WordPress PHP function outputs the class names for the HTML body element. This function aids in applying distinct styles to different parts of your WordPress site.

Table of contents

Usage

Here’s a simple usage of the function where we add a custom class ‘my-custom-class’:

<body <?php body_class('my-custom-class'); ?>>

In the rendered HTML, this might appear as:

<body class="page page-id-2 page-parent page-template-default logged-in my-custom-class">

Parameters

  • $css_class (string|string[]): Optional. Space-separated string or array of class names to add to the class list. Default is ” (empty string).

More Information

See WordPress Developer Resources: body_class()

Examples

Add a New Class to Body

add_filter( 'body_class', 'wp_body_classes' );

function wp_body_classes( $classes ) {
    $classes[] = 'new-class';
    return $classes;
}

In this example, the ‘new-class’ is added to the body classes.

Add a Class to a Specific Page Template

add_filter( 'body_class', 'custom_class' );

function custom_class( $classes ) {
    if ( is_page_template( 'page-example.php' ) ) {
        $classes[] = 'example';
    }
    return $classes;
}

Here, the ‘example’ class is added if the current page uses ‘page-example.php’ template.

Add Multiple Classes Conditionally

add_filter( 'body_class', 'wpdocs_custom_class' );

function wpdocs_custom_class( $classes ) {
    if ( is_page_template( 'page-example.php' ) ) {
        $classes[] = 'example';
    }
    if ( wpdocs_another_function() ) {
        $classes[] = 'another';
    }
    return $classes;
}

In this example, ‘example’ and ‘another’ classes are added based on certain conditions.

Remove a Specific Class from Body

add_filter('body_class', function (array $classes) {
    if (in_array('class-to-remove', $classes)) {
        unset( $classes[array_search('class-to-remove', $classes)] );
    }
    return $classes;
});

This example shows how to remove ‘class-to-remove’ from the body classes.

Add Class to Body on Specific Pages

add_filter( 'body_class', function( $classes ) {
    if ( is_page( 'login' ) ) {
        $classes[] = 'login';
    } elseif ( is_page( 'register' ) ) {
        $classes[] = 'register';
    } elseif ( is_page( 'password-reset' ) ) {
        $classes[] = 'reset';
    }
    return $classes;
});

In this example, depending on the page being viewed (‘login’, ‘register’, or ‘password-reset’), a specific CSS class is added to the body tag of the HTML document.

Leave a Comment

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