I've been searching for a while but I can't find how to remove woocommerce coupons programmatically.
I'm trying to make discounts based on cart total. I need to apply remove coupons because If you have products worth 1000 € (15% discount coupon applied) and remove products and leave only products worth 50 €, you still get this 15% discount because my code isn't removing the already applied coupon.
So here is my code for now:
add_action( 'woocommerce_before_cart', 'apply_matched_coupons' );
function apply_matched_coupons() {
global $woocommerce;
$coupon_code5 = '5p'; // your coupon code here
$coupon_code10 = '10p'; // your coupon code here
$coupon_code15 = '15p'; // your coupon code here
$coupon_code20 = '20p'; // your coupon code here
$coupon_code25 = '25p'; // your coupon code here
if ( $woocommerce->cart->has_discount( $coupon_code ) ){
return;
}
if ( $woocommerce->cart->cart_contents_total >= 4000 ) {
$woocommerce->cart->add_discount( $coupon_code25 );
$woocommerce->show_messages();
}
else if ( $woocommerce->cart->cart_contents_total >= 2000 ) {
$woocommerce->cart->add_discount( $coupon_code20 );
$woocommerce->show_messages();
}
else if ( $woocommerce->cart->cart_contents_total >= 1000 ) {
$woocommerce->cart->add_discount( $coupon_code15 );
$woocommerce->show_messages();
}
else if ( $woocommerce->cart->cart_contents_total >= 500 ) {
$woocommerce->cart->add_discount( $coupon_code10 );
$woocommerce->show_messages();
}
else if ( $woocommerce->cart->cart_contents_total >= 200 ) {
$woocommerce->cart->add_discount( $coupon_code5 );
$woocommerce->show_messages();
}
}
To remove a single coupon from the cart using its coupon code use WC_Cart->remove_coupon( $code )
.
To remove all coupons from the cart you would use WC_Cart->remove_coupons( $type )
- $type
defaults to null
for all, pass in "cart" to remove before tax coupons, "order" for after tax coupons.
To get all of the coupons in the cart as an array
you can loop over and optionally remove, use WC_Cart->get_coupons()
.
foreach ( WC()->cart->get_coupons() as $code => $coupon ){
$valid = ? // decide to remove or not
if ( ! $valid ){
WC()->cart->remove_coupon( $code );
}
}