WP Munk > Blog > Code Snippets > How to Add Custom Body Classes in WordPress

How to Add Custom Body Classes in WordPress

The “body_class()”  in WordPress adds classes to the body tag of all the pages in your WordPress site. By default a WordPress theme should use the function “body_class()” in their theme files so that WordPress can automatically output correct classes to each page/post and archive.

The following example shows how to implement the body_class template tag into a theme.

<body <?php body_class(); ?>>

The actual HTML output might resemble something like this:

<body class="page page-id-2 page-parent page-template-default logged-in">

If you want to add your own custom class to the body then the easiest way is to add a add the custom class in this format:

<body <?php body_class( 'class-name' ); ?>>

which will output something like this:

<body class="page page-id-2 page-parent page-template-default logged-in class-name">

But the problem with this approach is that the custom class “class-name” will be added to each and every page and post of your site.

Now, In case you want to add the custom class only to specific pages/posts or archives then use following function and edit as per your requirement:

function wphe_body_classes( $classes ) {
	global $post;
	
	if ( is_singular( 'post' ) ) {  
		$classes[] = 'class-name';  // add custom class to all single posts
	}
	
	if ( is_singular( 'page' ) ) {  
		$classes[] = 'class-name';  // add custom class to all single pages
	}	
	
	if ( is_singular( 'customposttype' ) ) {  // change customposttype to your CPT slug
		$classes[] = 'class-name';  // add custom class to all single custom post types
	}		
	
	if ( is_home() ) {  
		$classes[] = 'class-name';  // add custom class to blog homepage
	}			
	
	if ( is_front_page() ) { 
		$classes[] = 'class-name';  // add custom class to blog static page frontpage
	}				
	
	if ( is_archive() ) { 
		$classes[] = 'class-name';  // add custom class to archive pages
	}					

	return $classes;
}
add_filter( 'body_class', 'wphe_body_classes' );

About The Author


Mohammad Tajim

Hello, I am Mohammad Tajim a WordPress Developer with over 14 years of experience building WP Products. I made Munk WordPress Theme and other themes available at metricthemes.com. Follow me on twitter @tajim

More free templates for download at: Google Slides Themes

Copyright © 2020 WP Munk.
Built with Munk and Powered by WordPress.