Add Custom Body Class Based on Permalink Slug

This code adds a custom body class when the permalink contains the slug test-slug. If it doesn’t, no custom body class is added.

Could also be written like this :

add_filter( 'body_class', 'add_my_page_body_class' );
function add_my_page_body_class( $classes ) {

	  $ternary = strpos($_SERVER['REQUEST_URI'], 'test-slug' ) ? 'custom-body-class' : '';
	  
	  $classes[] = $ternary;
	  
	  return $classes;
	
}

Or like this :

add_filter( 'body_class', 'add_my_page_body_class' );
function add_my_page_body_class( $classes ) {
	  
	  $classes[] = strpos($_SERVER['REQUEST_URI'], 'test-slug' ) ? 'custom-body-class' : '';
	  
	  return $classes;
	
}

Based on a question from a member of the Genesis community.

This code uses a ternary operator however you could also use a else if statement.

Works in any WordPress theme.

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.