If you want to add a custom CSS class to the body tag of your website on all the posts and pages, use the following code. It adds a filter function to the body_class filter and adds a custom CSS class to the body tag of all the pages on your website.
To add a custom CSS class to the body tag, put the following code in your functions.php file or a custom plugin:
function add_custom_body_classes($classes) {
$classes[] = 'my-custom-body-class';
$classes[] = 'my–second-custom-body-class';
return $classes;
}
add_filter('body_class', 'add_custom_body_classes');
The above code will add a filter function called add_custom_body_classes to the body_class filter. The filter function adds two custom classes as an example. If you only want to add one class, replace the class name in the second line and remove the third line of code. Or if you want to add more classes, just duplicate the second line of code and and replace the custom class with your preferred one.
For the above code to work, your theme needs to call the body_class function on the opening body tag to add CSS classes to it. If your theme doesn’t do so already, add it yourself:
<body <?php body_class() ?>>
Replace the opening body tag in your theme’s header.php file with the above code if it doesn’t already look like this.
Leave a Reply