Using WordPress ‘get_body_class()’ PHP function

The get_body_class() WordPress PHP function retrieves an array of the class names for the body element.

Usage

get_body_class( string|array $css_class = '' );

Parameters

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

More information

See WordPress Developer Resources: get_body_class

Examples

Check if the home class is present

// Check if the "home" class is present in the body element
if (in_array('home', get_body_class())) {
    // The "home" class is present
} else {
    // The "home" class is not present
}

Add a custom class to the body element

// Add a custom class to the body element
$body_classes = get_body_class( 'custom-class' );

Add multiple custom classes to the body element

// Add multiple custom classes to the body element
$body_classes = get_body_class( array( 'custom-class-1', 'custom-class-2' ) );

Display body classes as a space-separated string

// Retrieve body classes and display them as a space-separated string
echo '<body class="' . join( ' ', get_body_class() ) . '">';

Remove a specific class from the body element

// Remove a specific class from the body element
$body_classes = get_body_class();
if (($key = array_search('class-to-remove', $body_classes)) !== false) {
    unset($body_classes[$key]);
}