Development & EngineeringMar 16, 2021
Extend WordPress Body with an Additional CSS Class using PHP.
Sometimes it is helpful to add an additional class to a page depending on a condition. Thanks to WordPress's filter system, adding more classes is a breeze.
First, open the functions.php file located in the child theme of your WordPress instance.
Add Multiple CSS Classes to the Body of WordPress via Filter
Using the body_class filter, you can extend the CSS classes that are applied to the body. You can add as many classes as you like.
add_filter('body_class', 'addCustomClasses', 10, 1);
/**
* Add custom CSS classes to the body
* @param array $classes
* @return array
*/
function addCustomClasses($classes){
$customClasses = array('css-class-1', 'css-class-2');
return array_merge($classes,$customClasses);
}
Object-Oriented Method to Add Multiple CSS Classes to the Body of WordPress via Filter
Of course, this can also be easily implemented in an object-oriented way.
/**
* Class to add additional CSS classes to the body
*/
class CustomizeBody{
/**
* Constructor
*/
public function __construct(){
add_filter('body_class', array($this, 'addClasses'));
}
/**
* Add CSS classes
* @param string $classes
* @return array
*/
public function addClasses($classes){
$customClasses = array('css-class-1', 'css-class-2');
return array_merge($classes,$customClasses);
}
}
new CustomizeBody();
Adding CSS Classes to the Body of WordPress with a Condition
You can certainly extend the function as desired and also integrate conditions. For example, you can add a CSS class to the body based on the post ID.
add_filter('body_class', 'addCustomClasses', 10, 1);
/**
* Add custom CSS classes to the body
* @param array $classes
* @return array
*/
function addCustomClasses($classes){
global $post;
$customClasses = array('css-class-1', 'css-class-2');
if(null != $post && $post->ID == 12345){
$classes = array_merge($classes,$customClasses);
}
return $classes;
}
Removing a CSS Class from the Body
Of course, you can also remove classes from the body. While this is rather unusual, it can still be helpful at times.
add_filter('body_class', 'removeClasses', 10, 1);
/**
* Remove custom CSS classes from the body
* @param array $classes
* @return array
*/
function removeClasses($classes){
$cssClassesToRemove = array('css-class-1', 'css-class-2');
foreach($classes as $key => $value){
if(in_array($value, $cssClassesToRemove)){
unset($classes[$key]);
}
}
return $classes;
}
That's it!
In this short tutorial, we looked at how to add custom CSS classes to the body of WordPress.
We also learned how adding class names can be linked with a condition. Additionally, we saw how the filter can be implemented using object-oriented programming.
Finally, we also looked at how to remove multiple classes from the body in case you actually need this functionality.