How to Apply Coupons Programmatically in WooCommerce?

GET IN TOUCH

Need to Fix Your WordPress Site?

What is Coupon?

  • a voucher entitling the holder to a discount off a particular product.
  • a form in a newspaper or magazine which may be sent as an application for a purchase or information.

Giving Coupons to your customers is another good way to drive sales. In WooCommerce, Coupons generally added to the products in the cart or the products in the order.

How to do it In Cart?

$coupon_code = '20%OFF';
WC()->cart->apply_coupon( $coupon_code );

If you want to check whether a coupon is already applied, then need to use has_discount().

if ( ! WC()->cart->has_discount( $coupon_code ) ) {
  WC()->cart->apply_coupon( $coupon_code );
}

Let’s put these code in our theme function file or as a custom plugin.

add_action( 'woocommerce_add_to_cart', 'wc_apply_coupon' );

function wc_apply_coupon() {
	$coupon_code = '20%OFF';
	if ( WC()->cart->has_discount( $coupon_code ) ) {
		return;
	}
	WC()->cart->apply_coupon( $coupon_code );
}

Well if you want to add that coupon code for a spesific product then we can do it as well.

add_action( 'woocommerce_add_to_cart', 'wc_apply_coupon_for_specific_product', 10 );
function wc_apply_coupon_for_specific_product() {
	$coupon_code = '20%OFF';
	$product_id = 14;
	
	if( in_array( $product_id, array_column( WC()->cart->get_cart(), 'product_id' ) ) ) {
		if( ! WC()->cart->has_discount( $coupon_code ) ) {
			WC()->cart->apply_coupon( $coupon_code );
		}
	} else {
		WC()->cart->remove_coupon( $coupon_code );
		WC()->cart->calculate_totals();
	}
}

We can apply a coupon depending on the number of products in the cart. We can use this code: count( WC()->cart->get_cart() ). Also we can use WC()->cart->get_subtotal() to add coupn depending upon cart sub total amount.

Here is a blog, where I have explained how you can use discounts to boost sales. Thank you for reading this article.

Tags:

Response to “How to Apply Coupons Programmatically in WooCommerce?”

  1. WooCommerce Tips and Tricks – We Build & Deploy Powerful Application

    […] How to Apply Coupons Programmatically in WooCommerce? […]

Leave a Reply

Your email address will not be published. Required fields are marked *