Reputation: 57
Currently this is what it shows in our site with the current code:
The current code shows all the stocks before even clicking on any of the variation/sizes. What our client wants is to only show that specific variation's stock quantity once they are clicked/selected on the drop down. Does anyone have an idea how to do this?
Current Code:
add_action( 'woocommerce_before_add_to_cart_button', 'display_stock_variations_loop' );
function display_stock_variations_loop(){
global $product;
if ( $product->get_type() == 'variable' ) {
foreach ( $product->get_available_variations() as $key ) {
$attr_string = array();
foreach ( $key['attributes'] as $attr_name => $attr_value ) {
$attr_string[] = $attr_value;
}
if ( $key['max_qty'] > 0 ) {
echo '' . implode( ', ', $attr_string ) . ': ' . $key['max_qty'] . ' in stock<br>';
} else {
echo '' . implode(', ', $attr_string ) . ': out of stock<br>';
}
}
echo '<br>';
}
}
Upvotes: 1
Views: 833
Reputation: 253784
The displayed selected variation stock quantity and status is already managed by woocommerce. You just need to add your "Size" attribute term name value, using the following (without any javascript need):
add_filter( 'woocommerce_get_availability_text', 'filter_variations_availability_text', 10, 2 );
function filter_variations_availability_text( $availability_text, $product ) {
if( $product->get_type() == 'variation' && $product->get_attribute('size') ) {
$availability_text = $product->get_attribute('size') . ': ' . $availability_text;
}
return $availability_text;
}
Code goes in function.php file of your active child theme (active theme). Tested and works.
Upvotes: 1