How to add or remove coupons dynamically based on cart total, on WooCommerce

Imagine the scenario where we have 2 coupons, one (5off) that gives $5 discount to the total client order, as well as a coupon (10off) that gives $10 discount to the total client order.

When the user inserts any of the coupons in, we want the $10 off coupon to apply only if the total order value is over $50, otherwise, we want the $5 coupon to apply instead.

<?php
/**
* @snippet Add / Remove A Coupon Dynamically based on Cart Subtotal with WooCommerce
* @sourcecode https://wpharvest.com
* @author Dragos Micu
*/
add_action( 'woocommerce_calculate_totals', 'wpharvest_apply_coupons' );
function wpharvest_apply_coupons($cart) {
global $woocommerce;
// Set your coupon codes
$coupon10off = '10off';
$coupon5off = '5off';
// Get the cart subtotal
$cart_subtotal = $cart->subtotal;
// If cart subtotal is less than 50 add or remove coupons
if ($cart_subtotal < 50) {
if ( $woocommerce->cart->has_discount( $coupon10off ) ) {
$cart->remove_coupon( $coupon10off );
$woocommerce->cart->add_discount( $coupon5off );
}
}
// If cart subtotal is greater 49 add or remove coupons
if ($cart_subtotal > 49 ) {
if ( $woocommerce->cart->has_discount( $coupon5off ) ) {
$cart->remove_coupon( $coupon5off );
$woocommerce->cart->add_discount( $coupon10off );
}
}
}

Did this coupon stop working, or need help with a different integration? Leave us a comment below and we’ll be more than happy to assist you!

Leave a Reply

Your email address will not be published. Required fields are marked *