How to Add Custom Body Class in WordPress

In this post, we are going to take a look at body_class template tag and use it to add our own classes to <body> element in WordPress.

Quick Tip : Automatically Add a Class to the Attachment Images

This template tag adds a number of CSS classes to <body> element. This helps the WordPress theme developers for applying distinctive styles to different pages of WordPress Website.

There are two main ways to add a custom class to <body> element in WordPress,

1. By Passing class name to body_class method as parameter.

2. By using Body Class Filter.

01. By Passing class name to body_class method as parameter.

To add your own custom class to body tag, you can pass class name as parameter to the body_class function,

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

To add more than one class, you need to pass an array to the body_class function,

<body <?php body_class( array( "class-a", "class-b", "class-c" ) ); ?>>

You can also add classes conditionally depending on the page. In this example, we are going to add an additional class to body when a Single Post is being displayed.

<body <?php if ( is_page() ){body_class( 'single-post' );} else {body_class();} ?>>

02. By using Body Class Filter

You can also add additional classes by using body_class filter.

add_filter( 'body_class', 'custom_body_class' );
function custom_body_class( $classes ) {
	$classes[] = 'custom-class';
	return $classes;
}

To add multiple classes, all you need to do is add another value to the array,

add_filter( 'body_class', 'custom_body_class' );
function custom_body_class( $classes ) {
	$classes[] = 'custom-class-one';
	$classes[] = 'custom-class-two';
	return $classes;
}

You can also add classes conditionally,

add_filter( 'body_class', 'custom_body_class' );
function custom_body_class( $classes ) {
        if ( is_page() ) {
	     $classes[] = 'custom-class';
        }
        return $classes;
}

 

0 Comments

Leave a Comment.