Woocommerce从订单对象获取选定的变体

时间:2019-07-02 09:09:07

标签: woocommerce attributes product variations

我正在尝试从订单对象获取变化。这是我的代码:

// This is my order object.
global $order;

// I am getting items from order.
$items = $order->get_items();

// Get single item from items
foreach( $items as $item ) {
    // Get product id which i bought.
    $product_id = $item->get_product_id();

    // Get product object which i bought
    $product = wc_get_product( $product_id );

    // This is my problem! It gets all variations. I want to gent only selected when customer was buying.
    $product_variation_name = $product->get_attribute( 'my-custom-variation' );
}

正如我所说。我正在尝试从购买的订单中获取选定的变体。但是$product->get_attribute得到了所有的变化。

我的版本在产品页面上如下所示:

<select name="variation" id="variation">
    <option value="pa_my-custom-variation">My Custom Variation</option>
    <option value="pa_other-variation">Other Variation</option>
    <option value="pa_other-variation-1">Other Variation 1</option>
</select>

1 个答案:

答案 0 :(得分:0)

您应该先从商品中获取版本ID,然后再获取版本和属性

这对我有用

 $variation_id = $item->get_variation_id(); 
    $variation = new WC_Product_Variation($variation_id);
    $variationName = ' ' . implode(" - ", $variation->get_variation_attributes());