Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add woocommerce product type to body class array

I am trying to add Woocommerce product types to the Wordpress body tag class array thats called in header.php with

body_class();

I have the following function in functions.php but it is not adding the class. If I remove the conditional and just have

$classes[] = 'simple-product';

Then the class is added. I assume this is to do with an issue getting global values. I am calling in $woocommerce, $post and $product globals as I am not sure which I actually need.

//Add Woocommerce body classes
add_filter('body_class','ttm_woocommerce_body_classes');
function ttm_woocommerce_body_classes($classes){
    global $woocommerce, $post, $product;
    if ( $product->product_type == 'simple' ) $classes[] = 'simple-product';
    return $classes;
}

Thanks

like image 879
phantomdentist Avatar asked Jan 24 '26 20:01

phantomdentist


1 Answers

Have you tried var_dump($product) to see what (if anything) exists in that object?

According to the codex, you might have to populate it yourself using $post->ID, like so:

//Add Woocommerce body classes
add_filter('body_class','ttm_woocommerce_body_classes');
function ttm_woocommerce_body_classes($classes){
    global $post;
    $product = get_product( $post->ID );
    if ( $product->product_type == 'simple' ) $classes[] = 'simple-product';
    return $classes;
}
like image 95
Christian Avatar answered Jan 27 '26 15:01

Christian