I would like to show the stock status (eg. In Stock / Out of Stock) for each product variation shown in the drop down list of variations on the Woocommerce Product Page. I h
@LoicTheAztec
I have been using your updated code with the backorder function replacement too but come across an error due to a non-existent function call.
get_the_stock_status() is now get_stock_status() is it not ?
Anyhow, the updated code below fixes the issue and an issue I had with a gift card plugin that was failing to load due to the above error.
// Function that will check the stock status and display the corresponding additional text
function get_stock_status_text( $product, $name, $term_slug ){
foreach ( $product->get_available_variations() as $variation ){
if($variation['attributes'][$name] == $term_slug ) {
$is_in_stock = $variation['is_in_stock'];
$backordered = get_post_meta( $variation['variation_id'], '_backorders', true );
$stock_qty = get_post_meta( $variation['variation_id'], '_stock', true );
break;
}
}
$stock_status_text = $is_in_stock == 1 ? ' - (In Stock)' : ' - (Out of Stock)';
return $backordered !== 'no' && $stock_qty <= 0 ? ' - (On Backorder)' : $stock_status_text;
}
// The hooked function that will add the stock status to the dropdown options elements.
add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'show_stock_status_in_dropdown', 10, 2);
function show_stock_status_in_dropdown( $html, $args ) {
// Only if there is a unique variation attribute (one dropdown)
if( sizeof($args['product']->get_variation_attributes()) == 1 ) :
$options = $args['options'];
$product = $args['product'];
$attribute = $args['attribute']; // The product attribute taxonomy
$name = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title( $attribute );
$id = $args['id'] ? $args['id'] : sanitize_title( $attribute );
$class = $args['class'];
$show_option_none = $args['show_option_none'] ? true : false;
$show_option_none_text = $args['show_option_none'] ? $args['show_option_none'] : __( 'Choose an option', 'woocommerce' );
if ( empty( $options ) && ! empty( $product ) && ! empty( $attribute ) ) {
$attributes = $product->get_variation_attributes();
$options = $attributes[ $attribute ];
}
$html = '';
endif;
return $html;
}