write code to recalculate the order totals when I manually add a coupon to an order.

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.

write code to recalculate the order totals when I manually add a coupon to an order.

The robot generated the following code:

Here is a basic example of a WordPress code snippet which uses WooCommerce actions to recalculate the order totals on manually coupon addition. In this code, prefix 'nm_' is added to the function 'write_code' to avoid name collisions with other global function names.

“`php
add_action('woocommerce_before_calculate_totals', 'nm_write_code', 10, 1);

function nm_write_code($cart)
{
if (is_admin() && !defined('DOING_AJAX')) {
return;
}

if (did_action('woocommerce_before_calculate_totals') >= 2) {
return;
}

//Define your coupon code to be added
$coupon_code = 'my_coupon_code';

if (!$cart->has_discount($coupon_code)) {
$cart->add_discount($coupon_code);
}

foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
$product = $cart_item['data'];
$price = $product->get_price();
// Recalculate price according to the coupon applied
$new_price = $price – ($price * ($cart->get_coupon_discount_amount($coupon_code) / 100));
$product->set_price($new_price);
}
}
“`
In this code, we're hooking into `woocommerce_before_calculate_totals` to modify the cart totals before they're calculated by WooCommerce. For each item in the cart, we retrieve its product data, apply the coupon discount to its price, and set the new price on the product.

Please adapt this code according to your coupon calculation methodology, also ensure the usage of correct hooks based on where this code is to be applied as in on the cart page or checkout page etc.

**Remember:** Adjusting prices in WooCommerce in this way only changes the prices visually on the frontend. It doesn't actually change the product's price in the database.

This is a simple sample, your use case may require more advanced or specific customization which may need more sophisticated code.

And always backup your WordPress website before adding or modifying custom code.

**Disclaimer:** This piece of code is provided as is and it's always recommended to code review (or get someone to review it for you) as every WordPress installation is unique and this code might not work in your case, might conflict with other plugins or themes and it might negatively affect your WordPress installation. It’s always advisable to have a backup and be prepared

More
CODE SNIPPETS