Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Order item prices in Woocommerce 3

I need to change the item price in a woocommerce order but everything I found is to changing the price in the cart but this is not what I need because I need to change after the checkout process.

Does somebody can give me a clue on how to do that?

like image 416
Sergio Ríos Avatar asked Dec 23 '22 07:12

Sergio Ríos


1 Answers

You need to use the new CRUD setters methods introduced with Woocommerce 3:

  • For order object you will use WC_Order methods,
  • For order "line item" you will use WC_Order_Item_Product methods,
  • For both of them you could be also use some WC_Data methods like save()

Here is a working basic example with a static price and a static order ID:

$order_id = 809; // Static order Id (can be removed to get a dynamic order ID from $order_id variable)

$order = wc_get_order( $order_id ); // The WC_Order object instance

// Loop through Order items ("line_item" type)
foreach( $order->get_items() as $item_id => $item ){
    $new_product_price = 50; // A static replacement product price
    $product_quantity = (int) $item->get_quantity(); // product Quantity
    
    // The new line item price
    $new_line_item_price = $new_product_price * $product_quantity;
    
    // Set the new price
    $item->set_subtotal( $new_line_item_price ); 
    $item->set_total( $new_line_item_price );

    // Make new taxes calculations
    $item->calculate_taxes();

    $item->save(); // Save line item data
}
// Make the calculations  for the order and SAVE
$order->calculate_totals();

Then you will have to replace the static price by your submitted new price in your custom page, which is not so simple, as you will need to target the correct $item_id

like image 151
LoicTheAztec Avatar answered Jan 10 '23 03:01

LoicTheAztec