Getting the correct variation price from order ite

2019-08-23 05:01发布

问题:

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.

Code:

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

    }

回答1:

Updated 3

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.

The code:

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

Related:

  • Get Order items and WC_Order_Item_Product in Woocommerce 3

  • How to get WooCommerce order details



回答2:

Found the issue! - it was giving out wrong id replace:

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

with this:

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