Apply a Coupon Automatically Above a Cart Total
Adds an existing coupon to the cart as soon as the subtotal reaches an amount, and removes it again if the cart drops below, so shoppers never need to type a code.
Opens WPIDE on
Code
$wpide_auto_coupon = array(
'code' => 'spend100', // Existing coupon code.
'minimum' => 100, // Cart subtotal that triggers it.
);
add_action( 'woocommerce_before_calculate_totals', function ( $cart ) use ( $wpide_auto_coupon ) {
static $running = false;
if ( $running || ( is_admin() && ! wp_doing_ajax() ) || ! $cart instanceof WC_Cart ) {
return;
}
$running = true;
$code = wc_format_coupon_code( $wpide_auto_coupon['code'] );
$subtotal = 0;
foreach ( $cart->get_cart() as $item ) {
$subtotal += (float) $item['data']->get_price() * (int) $item['quantity'];
}
if ( $subtotal >= $wpide_auto_coupon['minimum'] && ! $cart->has_discount( $code ) && wc_get_coupon_id_by_code( $code ) ) {
$cart->apply_coupon( $code );
} elseif ( $subtotal < $wpide_auto_coupon['minimum'] && $cart->has_discount( $code ) ) {
$cart->remove_coupon( $code );
}
$running = false;
} );
Notes
Create the coupon in Marketing > Coupons first; its own usage limits and expiry still apply.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.