从 Woocommerce 3 中的订单中获取选定的变体属性

Com*_*ant 5 php wordpress product variations woocommerce

在 Woocommerce 中,我在管理区域有一份报告,记录了所售产品。网站上仅售出 5 种产品,但有些产品有 1 或 2 种变体。该报告效果很好,但忽略了变化。
我需要从订购的项目中检索属性值以准确显示数据。
我该怎么做呢?

get_variation_description() 没有按照我应用它的方式工作。

我的代码:

$order = wc_get_order( $vs); 

//BEGIN NEW RETRIEVE ORDER ITEMS FROM ORDER 
foreach( $order->get_items() as $item_id => $item_product ){
    $ods = $item_product->get_product_id(); //Get the product ID
    $odqty= $item_product->get_quantity(); //Get the product QTY
    $item_name = $item_product->get_name(); //Get the product NAME
    $item_variation = $item_product->get_variation_description(); //NOT WORKING
}
Run Code Online (Sandbox Code Playgroud)

Loi*_*tec 6

2020 年更新- 处理“自定义产品属性”(修改后的代码)

WC_Product 方法get_variation_description()已过时且已弃用。它被get_description()方法所取代。所以你需要先得到WC_Product对象。

要获取选定的变体属性,您将使用get_variation_attributes( )方法。

// Get an instance of the WC_Order object from an Order ID
 $order = wc_get_order( $order_id ); 

// Loop though order "line items"
foreach( $order->get_items() as $item_id => $item ){
    $product_id   = $item->get_product_id(); //Get the product ID
    $quantity     = $item->get_quantity(); //Get the product QTY
    $product_name = $item->get_name(); //Get the product NAME

     // Get an instance of the WC_Product object (can be a product variation  too)
    $product      = $item->get_product();

     // Get the product description (works for product variation too)
    $description  = $product->get_description();

    // Only for product variation
    if( $product->is_type('variation') ){
         // Get the variation attributes
        $variation_attributes = $product->get_variation_attributes();
        // Loop through each selected attributes
        foreach($variation_attributes as $attribute_taxonomy => $term_slug ){
            // Get product attribute name or taxonomy
            $taxonomy = str_replace('attribute_', '', $attribute_taxonomy );
            // The label name from the product attribute
            $attribute_name = wc_attribute_label( $taxonomy, $product );
            // The term name (or value) from this attribute
            if( taxonomy_exists($taxonomy) ) {
                $attribute_value = get_term_by( 'slug', $term_slug, $taxonomy )->name;
            } else {
                $attribute_value = $term_slug; // For custom product attributes
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

与所有其他产品类型一样经过测试并适用于产品变体……