In WooCommerce I am using the function below where it adds a sold out text on the product thumbnail if the product is out of stock:
add_action( 'woocommerce_before_shop_loop_item_title', 'bbloomer_display_sold_out_loop_woocommerce' );
function bbloomer_display_sold_out_loop_woocommerce() {
global $product;
if ( ! $product->is_in_stock() ) {
echo '<span class="soldout">Sold Out</span>';
}
}
It works for a simple product, but not for variable products.
For variable products with variations, if I set all variations to 0 stock quantity except for 1 variation, I notice that the sold out message still appears on the thumbnail. Technically this is not correct as we do have some in stock.
Does anybody know how to change the code below in order to handle this?
2
Answers
You can create a custom conditional function to check if all variations of a variable product are "out of stock" as follows:
Then you will use it in your revisited hooked function below:
Code goes in functions.php file of the active child theme (or active theme). It should works.
I made a lighter version of @LoicTheAztec ‘s function that will stop looping as soon as it finds a variable that is in stock:
Also with no fatal error because he made two critical typos in his function.
You can the do something custom like he did: