Skip to main content
Login Join
Snippet · PHP

Add custom classes to WordPress body

Shared by Hiral solanki · September 9, 2026 · @body_class

Back to Snippets

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' );
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments