Problem:
When displaying product variations in the WooCommerce Product Page dropdown, the stock status (e.g., In Stock/Out of Stock) for each variation is not readily available.
Solution:
Note: This solution is suitable for variable products with only one dropdown attribute.
Modify the wc_dropdown_variation_attribute_options function:
<code class="php">add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'show_stock_status_in_dropdown', 10, 2); function show_stock_status_in_dropdown( $html, $args ) { // Ensure there's only one variation attribute if( sizeof($args['product']->get_variation_attributes()) == 1 ) { $options = $args['options']; $product = $args['product']; $attribute = $args['attribute']; $name = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title( $attribute ); $show_option_none = $args['show_option_none'] ? true : false; if ( ! empty( $options ) ) { $html = '<select id="' . esc_attr( $id ) . '" class="' . esc_attr( $class ) . '" name="' . esc_attr( $name ) . '" data-attribute_name="attribute_' . esc_attr( sanitize_title( $attribute ) ) . '" data-show_option_none="' . ( $show_option_none ? 'yes' : 'no' ) . '">'; $html .= '<option value="">' . esc_html( $show_option_none_text ) . '</option>'; foreach ( $options as $option ) { $stock_status = get_stock_status_text( $product, $name, $option ); $html .= '<option value="' . esc_attr( $option ) . '" ' . selected( sanitize_title( $args['selected'] ), $option, false ) . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $option ) . $stock_status ) . '</option>'; } $html .= '</select>'; } } return $html; }</code>
<code class="php">function get_stock_status_text( $product, $name, $term_slug ) { foreach ( $product->get_available_variations() as $variation ){ if($variation['attributes'][$name] == $term_slug ) { $stock = $variation['is_in_stock']; break; } } return $stock == 1 ? ' - (In Stock)' : ' - (Out of Stock)'; }</code>
Usage:
Insert the above code snippets into your theme's functions.php file or a plugin file.
Limitations:
The above is the detailed content of How to Display Stock Status in WooCommerce Variation Dropdown for Single-Attribute Products?. For more information, please follow other related articles on the PHP Chinese website!