WordPress is most common CMS used all around the world. It is developer friendly cms that helps developers to customize as they want. Sometimes, developers need to add extra classes to body. In this blog post, we will discuss how to custom classes to body tag.
To add custom classes to the body tag you can use the body_class
hook.
To add one or more classes on the product page based on specific product categories you can use the Wordpress has_term
function (to check if a product belongs to that specific product category).
For this I created the array $classes_to_add
where:
- key: It can be the product category id (or the slug or the name). Or an array of them. Read the documentation.
- value: a string containing the classes to add to the body tag. If you want to add more than one class create a string with multiple values separated by a space (see my example below)
So:
// adds a class to the body element based on the product category
add_filter( 'body_class', 'add_body_class_based_on_the_product_category' );
function add_body_class_based_on_the_product_category( $classes ) {
// only on the product page
if ( ! is_product() ) {
return $classes;
}
// create an array with the ids (or slugs) of the product categories and the respective class (or classes) to add
$classes_to_add = array(
30 => 'class-1',
'cat_slug' => 'class-2 class-3',
32 => 'class-4 class-5', );
// if the product belongs to one of the product categories in the array it adds the respective class (or classes)
foreach ( $classes_to_add as $product_cat => $new_classes ) {
if ( has_term( $product_cat, 'product_cat', get_the_ID() ) ) {
$classes[] = $new_classes;
}
}
return $classes;
}
The code has been tested and works. Add it to your active theme’s functions.php.