Torque2
Torque2

Reputation: 87

Check if ANY coupon code is applied in WooCommerce

How do I check if ANY coupon is applied to a product in WooCommerce at checkout?

Everything I see checks for ID or slug, or an array of them, but I want to adjust some fields at checkout based on whether or not there's a coupon, any coupon.

Thanks in advance.

Upvotes: 6

Views: 11073

Answers (2)

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

You can use has_discount() function of the cart.. this needs the coupon code as argument.

Use it like this:

if (WC()->cart->has_discount('test1')) {
   // cart has coupon test1 applied
}

as suggested by @Anand, you can use WC()->cart->get_coupons(). This will return all the coupons if there are any in the cart.

However, as I've check woocommerce plugin source code, get_coupons() is using WP_Query. It's really not a big deal if there's no other better way.

Here's a better way. We can access a public variable of the cart applied_coupons. It contains an array of coupon codes applied to the cart. We can use it like this...

$has_coupons = count(WC()->cart->applied_coupons)>0?true:false;
if($has_coupons) {
   // cart has coupons
}

Upvotes: 4

Anand Shah
Anand Shah

Reputation: 14913

If you want to check for a specific coupon, @Reigel's answer is the solution. However to check if ANY coupon has been applied the following code will get the job done.

if( WC()->cart->get_coupons() ) echo "Coupon applied";

Upvotes: 10

Related Questions