Custom Body Class Function in your WordPress Theme

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:

Web Hosting
<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){
$classes[]='super-class';
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, 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. 

Conclusion

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 at Facebook and Twitter.

Articles Related to Theme Development From Scratch:

 

Editorial Staff

Prabhu Ganesan has provided his Web development and SEO services independently. He is Co-founder of Webicle Media and WPBlogX. He is very much involved in WordPress as it becomes a second nature for him. Find him on twitter @gprabhucbe

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.