Summary & Problem
Many store owners want WooCommerce to automatically apply a coupon when a customer buys a certain number of items. By default, WooCommerce only applies coupons after a customer enters a code manually. This article shows how to hook into WooCommerce cart events, check item quantities, and apply or remove a coupon programmatically.
How It Works
WooCommerce exposes hooks that fire whenever cart totals or item quantities change. We can use those hooks to inspect the cart. If a defined quantity is exceeded, the code applies the coupon using the apply_coupon()
method. A helper check using has_discount()
prevents duplicate coupons rudrastyh.com.
Code Snippet
Place the following code in your theme’s functions.php
file or a custom plugin. Replace your_coupon_code
with the coupon you created in WooCommerce, and adjust quantity_threshold
to the minimum number of items needed to trigger the discount.
/**
* Auto-apply a coupon when cart quantity meets threshold.
*/
add_action( 'woocommerce_after_cart_item_quantity_update', 'auto_apply_coupon_based_on_quantity', 10, 4 );
add_action( 'woocommerce_before_calculate_totals', 'auto_apply_coupon_based_on_quantity' );
function auto_apply_coupon_based_on_quantity( $cart_item_key = null, $quantity = null, $old_quantity = null, $cart = null ) {
// Set your coupon code and quantity threshold
$coupon_code = 'your_coupon_code';
$quantity_threshold = 3; // apply coupon when cart quantity is 3 or more
// Get total quantity of all items in the cart
$total_qty = 0;
foreach ( WC()->cart->get_cart() as $cart_item ) {
$total_qty += $cart_item['quantity'];
}
// Apply coupon if threshold met; otherwise remove it
if ( $total_qty >= $quantity_threshold ) {
if ( ! WC()->cart->has_discount( $coupon_code ) ) {
WC()->cart->apply_coupon( $coupon_code ); // applies coupon:contentReference[oaicite:1]{index=1}.
}
} else {
if ( WC()->cart->has_discount( $coupon_code ) ) {
WC()->cart->remove_coupon( $coupon_code );
WC()->cart->calculate_totals();
}
}
}
Explanation of the Code
woocommerce_after_cart_item_quantity_update
fires when a cart item quantity changes.woocommerce_before_calculate_totals
ensures the coupon logic runs during cart recalculation.WC()->cart->apply_coupon()
programmatically applies a couponrudrastyh.com, whilehas_discount()
checks whether it’s already applied.- The snippet also removes the coupon if the user reduces their item count below the threshold.
Conclusion
With this approach, you create a seamless checkout experience: customers don’t need to type a code and still get rewarded for buying more. Customize the quantity threshold and coupon code to fit your promotion.