I’m trying to update the quantities of an ordered product and when doing so I would like the order to reflect the actual cost. What I find happens is that the Product Cost is reduced to match the total and the order total is never actually updated. I’ve supplied a simple sample below:
function prefix_update_woo_order() {
$order_id = 123; // This needs to be a real order or there will be errors
$order_item_id = 5; // This needs to be a real order item ID or there will be errors.
$order = new WC_Order( $order_id );
$order_items = $order->get_items();
$order_items[ $order_item_id ]->set_quantity( 2 );
$order->calculate_taxes();
$order->calculate_totals();
$order->save();
}
add_action( 'admin_init', 'prefix_update_woo_order' );
For example, a “Beanie with Logo” product is on sale for $18.00 and I originally buy 1. I want to programmitically update the order item to a quantity of 2 instead of 1 after the order has been placed. I would expect the total to be $36.00 but what I’m finding is that the product cost changes to match the total price. Instead of a cost of $18.00 for a “Beanie with Logo” the quantity is updated to 2 and the cost is reduced to $9.00ea.
In short, what I want to do is update an existing order items quantity and have the totals updated to reflect the new quantity cost, discount, taxes. What methods do I need to use to achieve this?
4
Answers
This is what I've come up with. I've tried to use the
wc_format_decimal()
where applicable. Seems like a lot of work to simply update an order items quantity but it is what it is.The bottom comment is unnecessary but if you're using the Cost of Goods plugin then that will take care of that.
i have not tried what you are trying to achieve before. What i see in your code is that
$order_items
is an array of Items Objects produced fromWC_Order::get_items()
, but i dont see the WC_Order Instance being notified that the order items have changed. I would expect a method like$order->update_cart($order_items);
I believe i found some usefull links for more researchhttps://hotexamples.com/examples/-/WC_Order/-/php-wc_order-class-examples.html
woocommerce – programmatically update cart item quantity
Sorry, i was not much of help!
Use the follows code snippet to do the above task –
Codes goes to your active theme’s functions.php
Hello I think this code will change your problem