body_class
Filters the list of CSS classes on the <body> tag, so you can target specific pages from your stylesheet.
When it fires
WordPress applies body_class when the theme calls body_class() on the tag. Classic themes do this in header.php and block themes get it automatically. It only runs on front-end pages.
The main query has run by then, so you can use conditional tags to decide which classes to add.
Parameters
$classesstring[] |
An array of body class names. |
|---|---|
$css_classstring[] |
An array of additional class names added to the body. |
What to return
The array of class names. Add to it or remove from it, then return it.
Example: Add the page slug as a body class
add_filter( 'body_class', function ( $classes ) {
if ( is_singular() ) {
$slug = get_post_field( 'post_name', get_queried_object_id() );
if ( $slug ) {
$classes[] = 'slug-' . sanitize_html_class( $slug );
}
}
return $classes;
} );
Good to know
- Always return the array. Returning nothing causes an error when the classes are printed.
- The admin area has its own filter, admin_body_class, which works with a space-separated string, not an array.