Skip to content

Instantly share code, notes, and snippets.

@MWDelaney
Last active February 6, 2025 07:53
Show Gist options
  • Save MWDelaney/0200a347e552350398ee4fe4cc7a10ce to your computer and use it in GitHub Desktop.
Save MWDelaney/0200a347e552350398ee4fe4cc7a10ce to your computer and use it in GitHub Desktop.
WooCommerce: Prevent multiple coupons of the same "type" on a single order. This will, for instance, prevent coupon stacking if a customer or user has access to multiple Product % Discount or Cart % Discount coupons. Tested working with WooCommerce, WooCommerce Smart Coupons, and WooCommerce Points & Rewards
<?php
// Hook when a coupon is applied to a cart
add_action( 'woocommerce_applied_coupon', 'mwd_get_applied_coupons' );
// Get the current applied coupon and compare it with other applied coupons
function mwd_get_applied_coupons() {
// Get the currently applied coupon's type using the $_POST global to retrieve the current coupon's code
foreach ( WC()->cart->get_coupons() as $code => $coupon ) {
if($coupon->code == $_POST['coupon_code']) {
// Get this coupon's type so we can remove all other coupons of this type from the cart
$type_to_remove = $coupon->discount_type;
}
}
// Remove any other coupons of this type
// Loop through all other applied coupons
foreach ( WC()->cart->get_coupons() as $code => $coupon ) {
// Check whether each coupon matches the type of the coupon we just applied
if($coupon->code != $_POST['coupon_code'] && $coupon->discount_type == $type_to_remove) {
// Exclude "smart_coupon" type, since users should be able to use as many gift cards as they like
if($coupon->discount_type != 'smart_coupon') {
// Remove all coupons that match the type of the coupon we just applied
WC()->cart->remove_coupon( $coupon->code );
}
}
}
}
?>
@nevernotsean
Copy link

Hey thanks for the gist, this was super helpful. FYI your if($coupon->code == $_POST['coupon_code']) would come up as false when a user is on iOS. iOS autocapitalizes when typing, resulting in if( 'couponcode' == 'Couponcode' ) which would always be falsy. We replaced $_POST['coupon_code'] with strtolower($_POST['coupon_code']) and fixed the glitch.

Thanks again!

@rygramer
Copy link

Any suggestions on how to modify such that it prevents the stacking of ALL coupon types EXCEPT gift cards?

@iamjatinagrawal
Copy link

there are very simple settings in woocommerce that doesn't ask the code to be edited. just go to coupons and in usage restrictions tab, check the box where it says "individual use only". This will prevent the customer from applying multiple coupons.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment