How to add a body class in WordPress.

If you want to add your custom class in the body tag of WordPress you use the body class filter.
Some times you need a class according to your page or page template with the help of a body class filter you just add a class in the body tag based on your page or page template.

How body tage look like  in wordpress :  <body <?php body_class($bodyClasses); ?>>

Steps you flow to add the class in body tag:

  1. Open your wordpress function.php file on path (/wp-content/themes/community-boost/functions.php)
  2. Copy Code below
add_filter( 'body_class', function( $classes ) {
return array_merge( $classes, array( 'sidebar_content_template' ) );
} );

3. Past above Code into your function.php file .

4 . Check site body tage you have class “sidebar_content_template” in body tage ( you can replace this class with you custom class ).

Add class based on page slug or page template slug.

Example code below:

Here in the below code, you add a class on body tag base on the template assigned to the page
From the get_page_template_slug() function we get the slug name of the template assigned to the page and classes are added only those page body tags, not others.

add_filter( 'body_class', function( $classes ) {
    if( get_page_template_slug() =='abc_template.php') {
	    return array_merge( $classes, array( 'content_template' ) );
} );

Leave a Comment

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