I am trying to show each variable products stock quantity on the single product page in WooCommerce.
I have managed to show all the stock quantities for all the variations using the below code from Rodolfo Melogli of Business Bloomer but I would ideally like to only show a single stock quantity when each size option is selected.
Attached is a screenshot to explain it better.
The html output of the buttons:
<span class="ivpa_term ivpa_active ivpa_instock" data-term="l">L</span>
or when clicked
<span class="ivpa_term ivpa_active ivpa_clicked ivpa_instock" data-term="xl">XL</span>
As you can see it shows all the variations but I would just like to show the selected variations (S, M, L, XL etc.) quantities as highlighted in red.
Here is the PHP code:
add_action( 'woocommerce_after_add_to_cart_form', 'ocapparel_echo_stock_variations_loop' );
function ocapparel_echo_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 '<br/>' . implode( ', ', $attr_string ) . ': ' . $key['max_qty'] . ' in stock';
} else {
echo '<br/>' . implode(', ', $attr_string ) . ': out of stock';
}
}
}
}