I have been looking EVERYWHERE and I cannot seem to find a solution to a very simple problem. I have a Woocommerce store and I want to show to the user a message "Out of stock" next to the variation if it is out of stock. I do not want it grayed out, I want the user to be able to select it so they can view the price if they wish. Most snippets I find online only works when they product has ONE variation but I need it to work for at least two. My website sells mobile devices so for example:
If a user selects the storage as 64GB then the color list updates showing which colors are out of stock in 64GB. If all colors are out of stock then next to 64GB it shows "Out of stock" also.
If the color is selected first, then the storage – the color list is then updated with what is out of stock.
Can anyone help me out here? Going insane trying to get this working. The below code works to gray out out of stock products in the exact way I mentioned above (it works for multiple products) but I can’t figure out how to modify it for the use case mentioned above.
add_filter( 'woocommerce_variation_is_active', 'grey_out_variations_when_out_of_stock', 10, 2 );
function grey_out_variations_when_out_of_stock( $grey_out, $variation ){
if ( ! $variation->is_in_stock() ){
return false;
}else{
print_r($option_class);
return $term_name . ' - Out of Stock';;
}
}
2
Answers
You can check the availability of a product variation only if all but one of the attributes have been selected, not before.
All the necessary data is present on the product page and therefore you can use a jQuery script to process it.
In the variation form there is the
data-product_variations
attribute which contains an array with all the details of the product variations (variation id, stock status, attributes it uses, etc …).You can then make a comparison between the selected attributes and possible product variations.
The idea is this:
woocommerce_update_variation_values
event which fires after updating the options via Ajax (otherwise the changes will be overwritten)The code has been tested and works. Add it to your active theme’s functions.php.
RESULT
RELATED ANSWERS