# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [WooCommerce](https://wpide.com/library/category/woocommerce/)
- Requires: WooCommerce
- Tags: woocommerce, coupons, discounts, cart
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/woo-auto-apply-coupon/

## Code

```php
$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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Apply a Coupon Automatically Above a Cart Total" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
