Filter Hook since 2.8.0
body_class
Filters the CSS classes on <body>
Description
body_class lets CSS target context without extra wrappers. Return the array — do not echo class names.
When it runs
When body_class() prints the body tag in the template.
Signature
apply_filters( 'body_class', string[] $classes, string[] $css_class );Parameters
$classesstring[] — Body class names.$css_classstring[] — Additional classes passed to body_class().
Examples
Basic
add_filter( 'body_class', function( $classes ) {
if ( is_user_logged_in() ) {
$classes[] = 'user-logged-in';
}
return $classes;
} );Add a logged-in class for CSS and JS hooks.
Real case
add_filter( 'body_class', function( $classes ) {
if ( is_singular( 'book' ) ) {
$classes[] = 'book-' . get_post_field( 'post_name' );
}
return $classes;
} );Add a slug-based class for per-book styling hooks.
Common Use Cases
- Add role-based body classes
- Target specific page templates via CSS
- Add device detection classes
- Inject A/B test variant classes
Common mistakes
- Returning a string instead of the $classes array
Related hooks
FAQ
Can I remove a default body class instead of adding one?
Yes — search $classes with array_search() and unset() the key, then return the array.
Source: wp-includes/post-template.php