Part 5: How to Include Custom Body Class Function in your WordPress Theme?

Body class is a WordPress function that lets the body element to give different classes so the WordPress developers or the theme developers can style their website with CSS. It can represented as body_class() function. By using this function, you can easily modify the style of each page using CSS. This function is mainly used to apply different styles to different pages for your WordPress website.  You can define the body class function as: 

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

You can even pass arguments to this body class  function as 

<body <?php body_class(‘class-new’); ?>>  // this will add the body class of ‘class_new ’ to every page of your website.

In some cases, you may be required to add more than one body class. You can create them by the array as such:

<body <?php body_class(“class1”, “class2”, “class3”); ?>>// it takes all the classes and passes them through body-class function.

Example of an adding custom body class

Add the following lines of code in the functions.php file

function prabhu($classes){
return $classes;
add_action('body_class', 'prabhu');

And then specify the body class function in header.php

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

You can add body class to a specific page, a specific category, tag, archives etc. 

To check the status of your code, go to your page and right-click. You will find an option called  “Inspect”. Clicking on that you will find your body class on the source page. 

Add body class to WooCommerce product page

Working with WooCommerce custom code is pretty straightforward because the original WooCommerce layouts are still in use.
Here’s how to apply CSS on the single product page based on the product category:

add_filter( 'body_class', ‘yay_wc_product_cats_css_body_class' );
        function yay_wc_product_cats_css_body_class( $classes ){
  			if ( is_singular( 'product' ) ) {
    				$current_product = wc_get_product();
    				$custom_terms = get_the_terms( $current_product->get_id(), 'product_cat' );
    				if ( $custom_terms ) {
      					foreach ( $custom_terms as $custom_term ) {
        					$classes[] = 'product_cat_' . $custom_term->slug;
  			return $classes;

Customise WooCommerce email templates
If you don’t want to accidentally break your site while trying customising Woo emails, using a WooCommerce email customiser like YayMail will help a ton!

The YayMail plugin can also help developers conduct the clients’ requests without having to code from scratch.


Hope you understood the basis of body class function, and how to use them in your theme. If you have any queries or comments, please feel free to comment to us, you can subscribe to us on Facebook and Twitter.

Articles Related to Theme Development From Scratch:


Leave a Comment