The WPFolks app is out on iPhone and Android. Free, no ads. Download on the App Store Get it on Google Play
Skip to main content
Login Join
Snippet · PHP

Add custom classes to WordPress body

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

40 views
1 upvote
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

1 comment

  1. Amit Dholiya
    Amit Dholiya @amitdholiya

    This is used to add custom classes to the body tag based on page or conditions — handy for targeting specific templates with CSS/JS without touching the theme markup.

    Report

Proudly supported by