How to apply coupon in WooCommerce programmatically?

Do you want to create smart coupons and increase customer engagement? In this guide, we’ll show you how to create and apply a coupon in WooCommerce programmatically. We’ll show you different examples of what you can do to increase your sales.

Why use coupons in WooCommerce?

Most eCommerce sites have conversion rates that rarely exceed 3% so store owners are always looking for ways to increase their sales. One of the most effective ways to achieve that is by using discount coupons. Discounts can provide users with an extra benefit that can help them make up their minds and buy your product.

For example, you could use coupons for important eCommerce dates such as Christmas or Black Friday, offer discounts for a limited time, create coupons for your most loyal customers, and so on. There are many ways in which offering coupons can help increase conversion rates and you boost your sales. That’s why in this guide, we’ll show you how to create and apply coupons in WooCommerce programmatically.

How to create and apply a coupon in WooCommerce programmatically?

In this tutorial, you will learn how to create and apply WooCommerce coupons in different ways:

  1. Create WooCommerce coupons
  2. Apply coupon to:
    1. All products
    2. Specific products by ID
    3. The subtotal cart value
    4. The total cart depending on the number of products

As you will edit the functions.php file of the child theme, before you start you need to install a child theme. You can either create one or use a child theme plugin.

Additionally, keep in mind that we’ll use several WooCommerce hooks so, if you’re not familiar with them, we recommend you have a look at this post.

1) Create coupons in WooCommerce settings

Before applying coupons, you need to create them. So, the first step is to create a coupon in WooCommerce. Using the inbuilt WC feature you can easily create them in a few clicks.

So, in the WordPress dashboard, go to WooCommerce > Coupons and click Add coupon. In some WooCommerce versions, you may find it under Marketing > Coupons.

Then enter a coupon code name. You can either type any name you want or use an auto-generated name. In this case, we’ll name it auto_coupon.

Then, you have to choose the discount type (percentage, fixed cart discount, or fixed product discount), the amount (percentage or fixed amount), and the expiry date. You can also set restrictions terms of the products that the coupon applies for, the minimum amount that customers need to spend to apply the coupon, limit the usage per coupon or user, and many others.

After you’ve set up your coupon, press Publish.

Create woocommerce coupon

It’s worth noting that you can change any of these settings at any point. Just be aware that if you do it, you’ll need to adjust the scripts we’re going to use to match the new coupon code’s settings.

Now you know how to create coupons in WooCommerce. Let’s have a look at how to apply them.

2.1) Apply coupon to any product

First, let’s see how to apply a coupon to any WooCommerce product. For this, we’ll use the woocommerce_before_cart hook to run the script before the cart page loads.

Additionally, we’ll work with the WooCommerce cart object to retrieve the information we need to run our validation before applying the coupon code we’ve just created (auto_coupon).

The WC()->cart object is available in front end pages and it allows you to retrieve all the information related to the cart page.

So, paste the following script in the functions.php file of your child theme:

add_action( 'woocommerce_before_cart', 'QuadLayers_apply_coupon' );
    function QuadLayers_apply_coupon() {
        $coupon_code = 'auto_coupon';
        if ( WC()->cart->has_discount( $coupon_code ) ) return;
        WC()->cart->apply_coupon( $coupon_code );
        wc_print_notices();
    }

As you can see, we are using an if() conditional to check if the coupon has been already applied. To know that, you retrieve the WC cart object like this: WC()->cart->has_discount($coupon_code);

It’s important to note that you’ll need this kind of validation in every single case. If you don’t do this the right way, you will have coupon added multiple times, or when the cart page is reloaded.

Also, note that WC()->apply_coupon($coupon_code) is how you apply the defined coupon to the current cart page.

2.3) Apply WooCommerce coupons to specific product IDs

Another interesting option is to apply a coupon to specific WooCommerce product IDs. To do that, you can use the following script. Just make sure you edit the $products_id() array to match your product IDs.

add_action( 'woocommerce_before_cart', 'QuadLayers_apply_matched_id_products' );
function QuadLayers_apply_matched_id_products() {  
    
    // previously created coupon;
    $coupon_code = 'auto_coupon'; 
    // this is your product ID/s array  
    $product_ids = array( 664,624,619 ); 
    // Apply coupon. Default is false
    $apply=false;
 
    // added to cart products loop
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {                      
        if ( in_array( $cart_item['product_id'], $product_ids )):              
            // Id of product match
            $apply=true;
            break;                     
        endif;  
    }
    // apply & remove coupon
    if($apply==true):
        WC()->cart->apply_coupon( $coupon_code );
        wc_print_notices();  
    else:    
        WC()->cart->remove_coupons( sanitize_text_field( $coupon_code ));
        wc_print_notices();   
        WC()->cart->calculate_totals();    
    endif; 
}

Here, we’ve used a foreach() loop to loop over all the products that were added to the cart. If any of them matches with the specified IDs, the $apply variable is set to true.
This way, the validation simply applies the coupon when the variable is true. Otherwise, it removes the coupon.

2.4) Apply coupon to the subtotal cart value

Now, let’s say that instead of give discounts based on the products, you want to apply a coupon in WooCommerce when customers spend more than $50 in your store for example. This is a great way to reward your shoppers and encourage them to spend more money on your site.

So, with the following function, you can apply a coupon only when the cart subtotal value is more than 50.

add_action('woocommerce_before_cart','QuadLayers_apply_coupon_cart_values');
function QuadLayers_apply_coupon_cart_values(){
      
       // previously created coupon
       $coupon_code = 'auto_coupon';           
       // get coupon
       $current_coupon = WC()->cart->get_coupons();
       // get Cart subtotal
       $cart_ST = WC()->cart->subtotal;        
 
       // coupon has not been applied before && conditional is true
       if(empty($current_coupon)&&$cart_ST>=50):
           // Apply coupon
           WC()->cart->apply_coupon( $coupon_code );
           wc_print_notices();            
       // coupon has been applied && conditional is false
       elseif(!empty($current_coupon)&&$cart_ST<50):
           WC()->cart->remove_coupons(sanitize_text_field($coupon_code));
           wc_print_notices();       
           WC()->cart->calculate_totals();
           echo '<div class="woocommerce_message">Coupon was removed</div>';
       // Conditional is FALSE && no coupon is applied
       else:// Do nothing 
           echo '<div class="woocommerce_message"> Unknown error</div>';
       endif;
}

Of course, you can replace $50 in the script for any other amount that makes more sense for your business.

Apply WC coupon when total cart exceeds 50

Also note that in the conditional, we’re using the same WC object instances that we used before to control exactly when we add or remove the coupon. The WC()->cart->subtotal allows you to know the cart subtotal, storing its value in the $cart_ST variable.

Finally, keep in mind that you must use WC()->cart->calculate_totals();to recalculate the total amount of the cart after applying the coupon.

2.5) Apply coupon to the total cart depending on the number of products in the cart

Similarly, you can use the following script to apply a WooCommerce coupon only when there’s a minimum number of products in the cart. For example, let’s say you want to give your customers a discount when they have 4 or more products in their carts:

add_action('woocommerce_before_cart','QuadLayers_apply_coupon_cart_values');
function QuadLayers_apply_coupon_cart_values(){ 
        
        // previously created coupon
        $coupon_code = 'auto_coupon';            
        // get coupon
        $current_coupon = WC()->cart->get_coupons();       
        // get products count
        $P_count =WC()->cart->get_cart_contents_count();

        // coupon has not been applied before && conditional is true
        if(empty($current_coupon)&&$P_count>=4):
            // Apply coupon
            WC()->cart->apply_coupon( $coupon_code );
            wc_print_notices();             
        // coupon has been applied && conditional is false
        elseif(!empty($current_coupon)&&$P_count<4):
            // remove coupon
            WC()->cart->remove_coupons( sanitize_text_field( $coupon_code ));
            wc_print_notices();        
            WC()->cart->calculate_totals();             
            echo '<div class="woocommerce_message"> Coupon was removed</div>';
        // Conditional is FALSE && no coupon is applied
        else:// Do nothing  
            echo '<div class="woocommerce_message"> Unknown error</div>';
        endif;
}

If 4 products to apply a discount coupon doesn’t make much sense for your business, you can replace it with any other number that you want.

The new variable used here is $P_count, where the quantity of the added to cart products are stored. This allows you to have a solid conditional that will add or remove the coupon only when is required.

Apply coupons in WooCommerce - Coupons depending on number of products

Those are just some examples of how you can apply a WooCommerce coupon programmatically but the possibilities are endless. Take these scripts as a base and unleash your creativity to create your own scripts!

WC object instances

This is the full list of the WC object instances we used in all the above scripts, plus some others that might be useful:

  • WC()->cart->apply_coupon(‘coupon_code’);
    Applies the specified coupon to cart totals.
  • WC()->cart->remove_coupons( ‘coupon_code’);
    Removes the specified coupon from cart totals.
  • WC()->cart->has_discount( ‘coupon_code ‘);
    Returns whether or not a discount has been applied.
  • WC()->cart->get_coupons();
    Gets the currently applied coupons if it exists.
  • WC()->cart->subtotal;
    Gets the subtotal cart value.
  • WC()->cart->get_cart_contents_count();
    Gets the number of items in the cart.
  • WC()->cart->get_cart()
    Returns the content of the cart in an array.
  • WC()->cart->calculate_totals();
    Recalculates the cart totals.
  • WC()->cart->total;
    Retrieves the cart total (after calculation).
  • WC()->cart->is_empty();
    Checks if the cart is empty. Returns bool.
  • WC()->cart->get_coupon_discount_amount( ‘coupon_code’ );
    Gets the discount amount for a specified coupon code.
  • WC()->cart->needs_payment();
    Checks if the payment is required. Returns bool.

Conclusion

All in all, discounts are an excellent way to encourage your customers to buy from your store and boost your sales. You can use them for important dates such as Christmas or Black Friday, to reward your loyal customers, or to promote larger sales.

In this guide, you’ve learned how to create a coupon in WooCommerce and how to apply it programmatically. Additionally, we’ve seen different examples to apply the coupons to:

  1. All the products
  2. Specific products by ID
  3. The subtotal cart value
  4. The total cart depending on the number of products in the cart

You can take these scripts as a base and customize them to make the most of coupons in your store.

Finally, it’s important to note that even though coupons and discounts can help you increase conversion rates, you shouldn’t overuse them. Make sure that you’re offering them to the right customers at the right time. Otherwise, if you constantly offer discounts to anyone, it may affect your reputation.

For more guides to customize your store programmatically, you can have a look at the following guides:

Did you use these scripts? Do you have any questions? Let us know in the comments section below!