Select Page

Want to add a CSS class to the body tag in WordPress? This can be easily done using WordPress Hooks. In this post, we will show you how to add CSS classes to the body tag in WordPress. Body tags are HTML elements that contain all the content of a webpage. They are used to structure and format the content on a webpage.

Adding a CSS class to the body tag can be very useful if you want to target specific pages or sections of your website with CSS. For example, you could add a class to the body tag of your blog’s homepage and then use that class to target the blog posts on that page with CSS.

Adding a CSS class to the body tag can be done using the body_class() function in WordPress. This function accepts a string or an array of CSS classes as its only parameter.

Here is an example of how to use the body_class() function:

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

In the example above, we are adding the “homepage” CSS class to the body tag. You can add multiple CSS classes to the body tag by separating them with spaces:

<body <?php body_class( 'homepage blog-post' ); ?>>

The example above would add both the “homepage” and “blog-post” CSS classes to the body tag.

You can also add CSS classes to the body tag using the add_filter() function. This function allows you to modify the output of the body_class() function.

Here is an example of how to use the add_filter() function:

<?php 
function my_custom_body_classes( $classes ) { 
	$classes[] = 'homepage'; 
	$classes[] = 'blog-post';
	return $classes; 
}
add_filter( 'body_class', 'my_custom_body_classes' );

In the example above, we are using the add_filter() function to modify the output of the body_class() function. We are adding the “homepage” and “blog-post” CSS classes to the body tag.

You can also add classes conditionally based on what page it is or what post type it is.

<?php 
function my_custom_body_classes( $classes ) { 
	if ( is_home() ) { 
		$classes[] = 'homepage'; 
	} elseif ( is_singular( 'post' ) ) { 
		$classes[] = 'blog-post'; 
	}
	return $classes;
}
add_filter( 'body_class', 'my_custom_body_classes' );

In the example above, we are adding the “homepage” CSS class to the body tag on the homepage and the “blog-post” CSS class to the body tag on single blog post pages.