Using WordPress ‘body_class’ PHP filter

The body_class WordPress PHP filter allows you to modify the list of CSS body class names for the current post or page.

Usage

add_filter('body_class', 'your_custom_function');
function your_custom_function($classes) {
    // your custom code here
    return $classes;
}

Parameters

  • $classes (string[]): An array of body class names.
  • $css_class (string[]): An array of additional class names added to the body.

More information

See WordPress Developer Resources: body_class Ensure that the filter function returns the array of classes after processing, or all of the classes will be cleared, impacting the visual state of the site.

Examples

Adding a custom class to the body

This code adds a custom class ‘my-custom-class’ to the body.

add_filter('body_class', 'add_my_custom_class');
function add_my_custom_class($classes) {
    $classes[] = 'my-custom-class';
    return $classes;
}

Adding a class based on post type

This code adds a class based on the current post type.

add_filter('body_class', 'add_post_type_class');
function add_post_type_class($classes) {
    if (is_singular()) {
        global $post;
        $classes[] = 'post-type-' . $post->post_type;
    }
    return $classes;
}

Adding a class for users who are logged in

This code adds a ‘logged-in’ class for logged-in users.

add_filter('body_class', 'add_logged_in_class');
function add_logged_in_class($classes) {
    if (is_user_logged_in()) {
        $classes[] = 'logged-in';
    }
    return $classes;
}

Removing a specific class from the body

This code removes the ‘example-class’ from the body.

add_filter('body_class', 'remove_example_class');
function remove_example_class($classes) {
    if (($key = array_search('example-class', $classes)) !== false) {
        unset($classes[$key]);
    }
    return $classes;
}

Adding a class based on the current day

This code adds a class with the current day of the week.

add_filter('body_class', 'add_day_of_week_class');
function add_day_of_week_class($classes) {
$classes[] = strtolower(date('l'));
return $classes;
}