从Woocommerce 3的订单商品中获得正确的变动价格 [英] Getting the correct variation price from order items in Woocommerce 3

查看:89
本文介绍了从Woocommerce 3的订单商品中获得正确的变动价格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为每个商品变体获得正确的价格,但是似乎只是在获得该商品变体的第一价格.不知道如何解决这个问题.

Im trying to get the correct price for each item variation however it only seems to be getting the first price of that product variation. Not sure how to solve this.

代码:

$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();
        }

    }

推荐答案

已更新3

要在订购商品为产品变体时获得正确的当前变化价格,这比您做的要简单得多.然后,您将使用 Woocommerce 3 CRUD设置和获取方法设置订单商品总计,保存并更新订单.

To get the correct current variation price when the order item is a product variation is much more simple than you are doing. Then you will use Woocommerce 3 CRUD setter and getter methods to set the order item totals, save it and update the order.

代码:

// 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

这种方法应该更好地工作.

It should better work this way.

相关:

如何获取WooCommerce订单详细信息

这篇关于从Woocommerce 3的订单商品中获得正确的变动价格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆