I need to recalculate the order totals after adding a coupon to a manual order on the back end. This should function as if I clicked the recalculate button after adding the coupon. use the “woocommerce_order_recalculate_coupons_coupon_object” to implement this, because “woocommerce_applied_coupon” only works when adding coupons to the cart on the front end.

WordPress AI Code Robot

Create WordPress code snippets for free without a developer!

{Name (First):7.3} requested the  following code from my WordPress AI Code Generator.

I need to recalculate the order totals after adding a coupon to a manual order on the back end. This should function as if I clicked the recalculate button after adding the coupon. use the "woocommerce_order_recalculate_coupons_coupon_object" to implement this, because "woocommerce_applied_coupon" only works when adding coupons to the cart on the front end.

The robot generated the following code:

Here is a basic example on how you might achieve this:

Please note this might still need adaptation according to your exact requirements and to ensure this code fits well within your existing codebase. Always remember to test in a staging environment first.

“`php
add_action( 'woocommerce_order_recalculate_coupons_coupon_object', 'nm_recalculate_order_after_coupon', 10, 5 );

function nm_recalculate_order_after_coupon( $coupon, $order, $items, $remove, $d ) {

//Check if coupon is being added and not removed.
if ( !$remove ) {
//Recalculate order total after adding coupon
$order->calculate_totals();

//Save the order
$order->save();
}

}
“`

This code snippet uses the `woocommerce_order_recalculate_coupons_coupon_object` action hook which is fired when a coupon is added or removed from an order in the backend. This allows you to add your own functionality at this stage of the process and in this case, we are making it recalculate the order totals.

The `calculate_totals` function is then called to update the totals for the cart, and the `save` function is called afterwards to save the changes to the order.

In other words, whenever a coupon is applied to a manual order (and not being removed), this should have the same effect as clicking the "recalculate" button. Just make sure to replace `nm_` in the function name with your theme's preferred prefix.

More
CODE SNIPPETS