How to add variation stock status to Woocommerce product variation dropdown

后端 未结 4 912
灰色年华
灰色年华 2020-11-27 08:17

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

4条回答
  •  无人及你
    2020-11-27 09:02

    Ok, first you'll need to get product variations like this:

    $variations = $product->get_available_variations();
    

    And inside options loop, you need to loop through the variations and find the current option stock status

    foreach ($variations as $variation) {
        if($variation['attributes'][$name] == $option) {
            $stock = $variation['is_in_stock'];
    
        }
    }
    

    Outside the variations loop you need to add the wording for in-stock and out-of-stock variations

    if( $stock == 1) {
        $stock_content = ' - In stock';
    } else {
        $stock_content = ' - Out of stock';
    }
    

    Then change the html to include an additional variable ($stock_content)

    $html .= ''; 
    

    So a complete function will look like this:

    add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'show_stock_status_in_dropdown', 10, 2);
    function show_stock_status_in_dropdown( $html, $args ) {
        $options = $args['options']; 
        $product = $args['product']; 
        $attribute = $args['attribute']; 
        $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' ); 
    
      // Get all product variations
        $variations = $product->get_available_variations();
    
        if ( empty( $options ) && ! empty( $product ) && ! empty( $attribute ) ) { 
            $attributes = $product->get_variation_attributes(); 
            $options = $attributes[ $attribute ]; 
        } 
    
        $html = ''; 
    
        return $html;
    }
    

提交回复
热议问题