How to Add Body Classes in WordPress

Sometimes you looking for add CSS Classes to body tag in WordPress theme for make some changes in style or control page for some reason so WordPress team provide body_class filter to can ease add CSS Classes here how to add CSS to body:
All you need to open your theme functions.php file and add this code:


function zytheme_add_body_classes( $classes ) {

	// add class if single post
	if ( is_single() ) {
		$classes[] = 'is-single';
	}

	// Adds a class if custom post type like portfolio
	if ( is_singular(portfolio ') ) {
		$classes[] = 'portfolio-class';
	}
	
	// add class if home page
	if (  is_home() ) {
		$classes[] = 'my-home';
	}

	// add class if user is admin
	if ( current_user_can('administrator) ) {
		$classes[] = 'is-admin';
	}

	return $classes;
}

add_filter( 'body_class', 'zytheme_add_body_classes' );

Please to work this code must body tag has body_class() function on it like that:


<body <?php body_class() ?>>

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply

Your email address will not be published. Required fields are marked *