Add custom CSS classes to the WordPress <body> element using the body_class filter.
This snippet demonstrates how to add classes based on the current page, post type, user state, or other WordPress conditions. It is useful for custom themes when you need to target specific pages or templates with CSS or JavaScript without modifying the theme’s HTML structure.
/**
* Add custom classes to the WordPress body element.
*
* @param array $classes Existing body classes.
* @return array
*/
function mytheme_custom_body_classes( $classes ) {
if ( is_front_page() ) {
$classes[] = 'is-homepage';
}
if ( is_singular() ) {
$classes[] = 'is-single';
}
if ( is_singular( 'post' ) ) {
$classes[] = 'is-blog-post';
}
if ( is_page() ) {
$classes[] = 'is-page';
}
if ( is_user_logged_in() ) {
$classes[] = 'user-logged-in';
} else {
$classes[] = 'user-logged-out';
}
return $classes;
}
add_filter( 'body_class', 'mytheme_custom_body_classes' );