{Name (First):7.3} requested the following code from my WordPress AI Code Generator.
When I apply a coupon manually to a woocommerce order, I want it to automatically recalculate the totals, as if I clicked the recalculate button.
The robot generated the following code:
You can achieve that by using the `woocommerce_applied_coupon` action hook that triggers when a coupon is applied. Then you can simply call the `calculate_totals` method to recalculate the totals.
Here is the Code snippet:
“`php
add_action( 'woocommerce_applied_coupon', 'nm_recalculate_totals', 10, 1 );
function nm_recalculate_totals( $coupon_code ) {
$wc_cart = WC()->cart;
$wc_cart->calculate_totals();
}
“`
In this case, the `nm_recalculate_totals` function will be fired when a coupon is applied. It fetches the current cart using `WC()->cart` and then recalculates the totals with the `calculate_totals` method.
Please make sure to use this code in your theme's `functions.php` file.
Remember that this is a simple approach and may need to be adjusted based on your specific needs and setup. Be sure to test this code thoroughly before applying it on a live website.