WooCommerce:使用延交订单阅读[max_qty]

时间:2017-09-28 作者:Geme

我需要在产品缺货时允许订购,并读取库存数量。如果我设置了allow backorder[允许延期交货],则以下代码的[最大数量]始终为0且不起作用:

 if ($product->product_type == \'variable\') {
        foreach ($product->get_available_variations() as $key) {
        $attr_string = \'\';
            foreach ( $key[\'attributes\'] as $attr_name => $attr_value) {
                                $attr_string[] = $attr_value;
            }
            if ( $key[\'max_qty\'] > 0 ) { echo \'<style> body span.swatch.swatch-label.swatch-\' . implode(\', \', $attr_string) . \' {opacity:1!important;     background: #484848!important; color: #fff!important;}</style>\'; } else {  }
            }
    }

1 个回复
SO网友:Geme

使用此代码解决:

if ($product->is_type( \'variable\' )){

    // Get the available variations for the variable product
    $available_variations = $product->get_available_variations();

    // Initializing variables
    $variations_count = count($available_variations);
    $loop_count = 0;

    // Iterating through each available product variation
    foreach( $available_variations as $key => $values ) {
        $loop_count++;
        // Get the term color name
        $attribute_color = $values[\'attributes\'][\'attribute_pa_size\'];
        $wp_term = get_term_by( \'slug\', $attribute_color, \'pa_size\' );
        $term_name = $wp_term->name; // Color name

        // Get the variation quantity
        $variation_obj = wc_get_product( $values[\'variation_id\'] );
        $stock_qty = $variation_obj->get_stock_quantity(); // Stock qty

        // The display
        $separator_string = " // ";
        $separator = $variations_count < $loop_count ? $separator_string : \'\';

       // echo $term_name . \' = \' . $stock_qty . $separator . \'<br>\';

         if ( $stock_qty > 0 ) { echo \'<style> body span.swatch.swatch-label.swatch-\' . $term_name.  \'{opacity:1!important;     background: #484848!important; color: #fff!important;}</style>\' ;} else {  }
    }

}

结束

相关推荐