This snippet adds custom CSS classes to the <body> tag on WooCommerce single product pages based on the product type. It helps developers apply custom styling or functionality for downloadable, variable, grouped, external, and simple products.
/**
* Add product type-specific CSS classes to the body element.
*
* This snippet appends custom body classes to WooCommerce
* single product pages based on the product type, allowing
* targeted styling and functionality for different product types.
*
* Added Classes:
* - is-downloadable-product
* - is-variable-product
* - is-grouped-product
* - is-external-product
* - is-simple-product
*
*/
function sj_add_product_type_body_class( $classes ) {
// Check if the current page is a single product page.
if ( is_singular( 'product' ) ) {
// Get the current WooCommerce product object.
$product = wc_get_product( get_the_ID() );
// Verify that the product exists.
if ( $product ) {
$product_type = $product->get_type();
// Add class for downloadable products.
if ( $product->is_downloadable() ) {
$classes[] = 'is-downloadable-product';
// Add class for variable products.
} elseif ( 'variable' === $product_type ) {
$classes[] = 'is-variable-product';
// Add class for grouped products.
} elseif ( 'grouped' === $product_type ) {
$classes[] = 'is-grouped-product';
// Add class for external products.
} elseif ( 'external' === $product_type ) {
$classes[] = 'is-external-product';
// Add class for simple products.
} else {
$classes[] = 'is-simple-product';
}
}
}
return $classes;
}
add_filter( 'body_class', 'sj_add_product_type_body_class' );