Home > Article > Backend Development > How to Display Stock Status for Product Variations in WooCommerce Dropdown?
How to Add Variation Stock Status to WooCommerce Product Variation Dropdown
Problem:
WooCommerce does not display the stock status for individual product variations within the dropdown list. This can make it difficult for customers to determine which variations are available.
Solution:
To add variation stock status to the dropdown, you can modify the wc_dropdown_variation_attribute_options function in your WooCommerce installation. This function generates the HTML that is displayed in the dropdown menu.
Code:
<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 ) { // Get the product and attribute. $product = $args['product']; $attribute = $args['attribute']; // Get the variations for the product. $variations = $product->get_available_variations(); // Loop through the variations and get the stock status for each one. foreach ( $variations as $variation ) { // Get the stock status. $stock_status = $variation['is_in_stock'] ? 'In Stock' : 'Out of Stock'; // Append the stock status to the HTML. $html .= '<option value="' . esc_attr( $variation['variation_id'] ) . '" ' . selected( $args['selected'], $variation['variation_id'], false ) . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $variation['attributes'][ $attribute ] ) ) . ' - (' . esc_html( $stock_status ) . ')</option>'; } return $html; }</code>
Explanation:
The above is the detailed content of How to Display Stock Status for Product Variations in WooCommerce Dropdown?. For more information, please follow other related articles on the PHP Chinese website!