从Woocommerce 3中的订单商品中获取正确的变化价格

时间:2018-06-14 11:13:22

标签: php wordpress woocommerce hook-woocommerce price

我试图为每个项目变化获得正确的价格,但它似乎只是获得该产品变化的第一个价格。不知道如何解决这个问题。

代码:

$query = new WC_Order_Query( array(
        'status' => 'on-hold',
        'orderby' => 'date',
        'order' => 'DESC',
        'return' => 'ids',
    ) );
    $order_ids = $query->get_orders();

    foreach( $order_ids as $order_id ) {


        $order = new WC_Order($order_id);


        foreach ($order->get_items() as $item_id => $item_obj) {
            $_product = wc_get_product($item_obj['product_id']);
            $product = new WC_Product_Variable($item_obj['product_id']);
            $product_variations = $product->get_available_variations();

            $variation_product_id = $product_variations [0]['variation_id'];

            $variation_product = new WC_Product_Variation( $variation_product_id );
            $t_dy =  $variation_product->get_price();
            $item_qty = $item_obj['qty'];
            $it_total = $item_qty * $t_dy;
            $td = wc_update_order_item_meta($item_id, '_line_total', $it_total);
            $order->calculate_totals();
            $order->save();
        }

    }

2 个答案:

答案 0 :(得分:2)

更新3

当订单商品是产品变体时,

获得正确的当前变动价格比您正在做的要简单得多。然后,您将使用Woocommerce 3 CRUD setter and getter methods设置订单项总计,保存并更新订单。

代码:

// Loop through order items
foreach ($order->get_items() as $item_id => $item ) {

    // Targeting only product variation items
    if( $item->get_variation_id() > 0 ){ 

        // Get an instance of the WC_Product_Variation object
        $product = $item->get_product(); 

        $price   = (float) $product->get_price(); // <=== HERE the variation price

        $qty     = (int) $item->get_quantity(); // <=== HERE the quantity

        // set line totals
        $item->set_total( $price * $qty );
        $item->set_subtotal( $price * $qty );

        $item->save(); // save order item data
    }
}

// The following need to be outside the order item loop
$order->calculate_totals(); // Save is included into the method

最好以这种方式工作。

相关:

答案 1 :(得分:0)

发现问题! - 这是错误的身份证明 替换:

 $variation_product_id = $product_variations [0]['variation_id'];

用这个:

$product_variation_id = $item_obj->get_variation_id();
$variation_product_id = $product_variation_id;
$variation_product = new WC_Product_Variation( $variation_product_id );