0

I have searched endlessly for this but I am yet to find a solution.

I have found ways to add custom classes through functions but can't seem to achieve through woocommerce where a custom class is added on the single product page when a product is out of stock.

Any pointers would be much appreciated.

0
add_filter('body_class', 'SE_314220_custom_outofstock_class');

 function SE_314220_custom_outofstock_class ($classes) {

  global $post;
  if($post->post_type !="product")
    return $classes;
  $product = wc_get_product( $post->ID );
  if($product->get_stock_quantity() ==0)
    $classes[] = 'OUT-OF-STOCK';
  return $classes;
}
0
0

I have updated the code from @Adnrea Somovigo and customize it, to display body classes, based on stock_status, not on stock_quantity. So this should work also for in-stock, on-backorder and out-of-stock stock statuses.

Stock quantity is not the correct parameter, because backorder products could have negative quantity (for example -6 pieces on stock) and products with 0 pieces could be either out-of-stock, or on-backorder.

add_filter('body_class', 'lava_stock_class');

 function lava_stock_class($classes) {
    global $post;
    if($post->post_type !="product")
        return $classes;
    $product = wc_get_product( $post->ID );
    if($product->get_stock_status() == 'outofstock') {
        $classes[] = 'outofstock';
    } elseif($product->get_stock_status() == 'onbackorder') {
        $classes[] = 'onbackorder';
    } else {
        $classes[] = 'instock';
    }

    return $classes;  
}
New contributor
Mego is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.