fbpx
How to apply WooCommerce coupons automatically

How to apply WooCommerce coupons automatically

Are you looking for ways to add discounts to your products to boost your sales? You’ve come to the right place. In this guide, we’ll show you how to apply WooCommerce coupons automatically.

We have previously seen how to create coupons in WooCommerce and some examples of how to apply them using code. This time, we’ll focus on how to automatically apply these discounts to surprise your shoppers and increase your sales.

Why apply WooCommerce coupons programmatically?

Offering coupons to users is a great way to boost your sales. By providing shoppers with a discount when they’re thinking about buying one of your products, you’ll encourage them to complete the purchase.

Converting visitors into customers by offering an attractive discount is a proven marketing strategy that most eCommerce websites take advantage of. However, it’s worth noting that the success of that offer will depend greatly on when you give the discount.

If you offer a discount to someone who’s just browsing, the offer is unlikely to have any effect. Similarly, if you reduce the price to someone who’s already decided where and what to buy, you may be too late to change their mind or reduce your revenue when you could have charged the full price. The best moment to give coupon codes is when shoppers are thinking about buying but haven’t made their final decision yet.

Discounts are also a great way to build a strong relationship with your recurring customers. By rewarding your customers with exclusive discounts, you’re giving them more reasons to come back to your store and become loyal users.

Limitations of default WooCommerce coupons

The default coupon functionality that WooCommerce offers works well, but it has some limitations. The biggest one is that users must enter coupons manually and refresh the page to apply the discount to their orders. As you can imagine, this extra friction isn’t ideal and can make you lose customers.

Additionally, it’s not possible to apply any kind of logical condition beyond the default ones which are related to the expiration date and the way the discount is applied. That’s why to take full advantage of coupons, you can customize their behavior and learn how to apply them programmatically.

In this guide, you will learn how to apply WooCommerce coupons automatically. This way, users won’t need to memorize the coupons, copy/paste them, or refresh the cart page. This will improve customer experience and help you boost your sales both in the short and long term.

How to apply WooCommerce coupons automatically

As we will edit the functions.phpfile, before you start with the process, we recommend you do a full backup of your site and install a child theme. You can either create a child theme or use a plugin. Additionally, we recommend you have a look at this guide if you’re not familiar with WooCommerce hooks.

Once you do that, let’s start by creating the coupon.

1) Create a WooCommerce coupon

First, in your WordPress dashboard, go to WooCommerce > Coupons/Marketing > Coupons and click Add coupon.

Create woocommerce coupon discount

Then, enter the name of the coupon. As this is what we will use to give discounts, we recommend a descriptive and simple name.

On top of that, you must specify other important information:

  • Amount of discount (fixed or percentage)
  • Type of coupon
  • Expiration date

You can also add some other options such as usage restrictions, limits per user, and so on. For more information on this, have a look at our guide on how to set up WooCommerce coupons.

Create woocommerce coupon settings

Once you’ve created the coupon, let’s see different ways to apply them automatically.

2) How to automatically add WooCommerce coupons

Before diving into the code, note that we are using the same “all-products” coupon code in all the following sample scripts. This code will apply a 3% discount on the subtotal.

Using this coupon in all cases may not make sense for your business, so make sure you adjust every script and edit the variable $coupon_code with your coupon code.

Now let’s see some examples of how to apply coupons automatically in WooCommerce.

2.1) Apply a coupon to returning customers

This will apply to the discount coupon only if the customer has previously completed an order.

// Returning customers
add_action( 'woocommerce_before_cart', 'QuadLayers_returning_customers_coupon' );
 
function QuadLayers_returning_customers_coupon(){
   $coupon_code = 'all-products';
   # Get customer orders
   $user_id = wp_get_current_user();
   $customer_orders = [];
   foreach ( wc_get_is_paid_statuses() as $paid_status ) {
       $customer_orders += wc_get_orders( [
           'type
'        => 'shop_order',
           'limit'       => - 1,
           'customer_id' => $user_id->ID,
           'status'      => $paid_status,
       ] );
       # apply coupon if there is an existing order
       if(count($customer_orders)>0){ 
           printf('<div class="woocommerce-message">This order applies for a discount because you are a returning customer!</div>');
           if ( WC()->cart->has_discount( $coupon_code ) ) return;
           WC()->cart->apply_coupon( $coupon_code );
           wc_print_notices();
           break;
       }   
   }
}

This is the result on the cart page:

Apply WooCommerce coupons automatically - Coupon for returning customers

As you can imagine, this requires users to be logged in to their accounts, because we need to get their user ID to check if they have existing orders.

If that condition is met, the discount will be applied and a message will be displayed on the cart.

To change the message, simply edit the printif line in the script.

2.2) Apply WooCommerce coupon on account user information

You can also apply a specified coupon depending on user account details. In the following sample script, we are going to apply the coupon only to customers that have entered the United States (US) as a country on their accounts. This can be an interesting option for targeted promotions to increase sales in certain markets or countries.

// Apply coupon on billing country (US)
add_action( 'woocommerce_before_cart', 'QuadLayers_customer_information_coupon' );
 
function QuadLayers_customer_information_coupon(){
   $coupon_code = 'all-products';
   $user = wp_get_current_user();
   $data = get_user_meta( $user->ID, 'billing_country', true );
   if($data=="US"):
   printf('<div class="woocommerce-message"> This order applies for a discount for US customers ! </div>');
           if ( WC()->cart->has_discount( $coupon_code ) ) return;
           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;
}

Besides adding the coupon when the user’s billing country is set to the United States, we are also removing the coupon if the country is not the US. If we don’t do that, a user could edit their billing address to get the coupon, and the coupon would remain there after going back to the original country.

2.3) Apply coupon on a schedule

The default WooCommerce options allow us to create coupons that apply to specific dates, or on a date schedule. But what if you need to apply a coupon on a daily schedule? Simply use the following script to apply the specified coupon only from 6:00 AM to 10:00 AM, for example.

This is an interesting option to launch flash sales and automatically apply coupons in WooCommerce.

// Apply coupon on a daily time schedule (06:00/10:00)
add_action( 'woocommerce_before_cart', 'QuadLayers_timer_scheduled_coupon' );
 
function QuadLayers_timer_scheduled_coupon(){
$blogtime = current_time( 'mysql' );
list( $today_year, $today_month, $today_day, $hour, $minute, $second ) = preg_split( "([^0-9])", $blogtime );
   $coupon_code = 'all-products';
   if($hour>=06&&$hour<10){
       printf('<div class="woocommerce-message">You are getting our good morning discount (from 6 to 10 AM) </div>');
           if ( WC()->cart->has_discount( $coupon_code ) ) return;
           WC()->cart->apply_coupon( $coupon_code );
           wc_print_notices();
   }
}

Note that we are retrieving the unique website time in our conditional and that’s coming from the server, so it will be the same hour regardless of the timezone in which the customer is located. To set specific times per timezone, you need to include extra logic.

2.4) Apply coupon on product tag taxonomy

This is a more complex function, where we retrieve all the tags of products added to the cart and check if a specific tag is present.

In the following example, the tag we use is “freeweek”, so before you do this, you need to create a tag and attach it to some products. Alternatively, you can use any of the tags that are already attached to your products.

// Apply coupon to product tag taxonomy (freeweek)
//
add_action( 'woocommerce_before_cart', 'QuadLayers_tag_coupon' );
 
function QuadLayers_tag_coupon() {
   $coupon_code = 'all-products';
   $id_a=array();
   foreach ( WC()->cart->get_cart() as $key => $cart_item ) {
       for ($i=0; $i < $cart_item['quantity'] ; $i++) {  
           $productId = $cart_item['data']->get_id();
           array_push($id_a,$productId);         
       }
   }
  
   for($t=0;$t<count($id_a);$t++){
       $terms = wp_get_post_terms( $id_a[$t], 'product_tag' );
       foreach($terms as $term){
               $term_name = $term->name; // Product tag Name
           if($term_name=='freeweek'):
                   printf('<div class="woocommerce-message">A product is tagged with a discount !</div>');
                   if ( WC()->cart->has_discount( $coupon_code ) ) return;
                   WC()->cart->apply_coupon( $coupon_code );
                   wc_print_notices();
               break;
           else:
                   WC()->cart->remove_coupons( sanitize_text_field( $coupon_code ));
                   wc_print_notices();  
                   WC()->cart->calculate_totals();
           endif;
       }
   }
}

This discount will be applied to all the products added to the cart that have the specified tag.

Once again, make sure to replace the “freeweek” tag name on the code with your product tag.

2.5) Apply coupon on a URL parameter

Another interesting application of coupon codes is using URL parameters to build a custom link. In a browser, a URL parameter and its value appear like this:

https://my.website.com/cart?parameter=value

This way, you can build a custom link and deliver it to your customers via email or phone. The coupon will be automatically applied to the order when anyone follows the link. Users who receive the link could share it with other users, so you may want to add some other conditions to make sure that only the customers you want have access to the discount.

// Apply coupon on URL parameter (?co=custom-link)
add_action( 'woocommerce_before_cart', 'QuadLayers_url_coupon' );
 
function QuadLayers_url_coupon() {
       $coupon_code = 'all-products';
   if(isset($_GET['co'])&&!empty($_GET['co']) ):
       $url_p=$_GET['co'];
       if($url_p=='custom-link'):
           printf('<div class="woocommerce-message">A product applies for a discount !%lt;/div>');
                   if ( WC()->cart->has_discount( $coupon_code ) ) return;
                   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;
   endif; 
}

As you can see, the custom link we’re using above is https://my.web?co=custom-link.

Bonus: Apply coupons to certain products

An interesting option is to automatically apply WooCommerce coupons to specific products. This way, you can make some products extra attractive to initially entice customers and then try to upsell them with other items.

To do this, use the following script and change the $products_id() array with your own 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; 
}

For more examples like this, have a look at our guide to create and apply coupons programmatically.

How to exclude products from coupons

Alternatively, you can exclude certain products from coupons so discounts don’t apply to them. This can be an interesting option if you sell items that already have a discount like bundled products or products that have low margins.

The good news is that you can do this from the WordPress admin dashboard. Go to Products > All Products, hover over the product you want to exclude from coupons, and write down the product ID.

Then, go to Appearance > Theme Editor > Theme functions and open the functions.php file. After that, paste the following code replacing the PRODUCT_ID with the ID of your product.

add_filter( 'woocommerce_coupon_is_valid_for_product', 'quadlayers_exclude_product_from_product_promotions', 9999, 4 );
function quadlayers_exclude_product_from_product_promotions( $valid, $product, $coupon, $values ) {
// REPLACE THE PRODUCT ID (E.G. 145)
if ( PRODUCT_ID == $product->get_id() ) {
$valid = false;
}
return $valid;
}

That’s it! The product that you choose won’t be affected by the coupons.

This is a simple example but there’s a lot more you can do. For more information about this, have a look at our tutorial to exclude WooCommerce products from coupons.

Conclusion

All in all, offering coupons to your shoppers is an excellent way to improve customer experience and increase your sales. Additionally, by giving your customers exclusive discounts, they’re more likely to become loyal to your store.

However, make sure you offer the discounts at the right time. Giving coupon codes too early or too late may not have the effect you expect, so use them smartly.

In this guide, we’ve seen that the coupon options WooCommerce has by default have some limitations. By learning how to apply WooCommerce coupons automatically, you’ll make your users’ life easier and improve their shopping experience on your site.

We’ve seen different examples to automatically apply coupons in different situations that will help you take your store to the next level. For more guides on WooCommerce coupons, make sure to check out the following posts:

Have you tried any of the above scripts on your site? Did they work as expected? Tell us your experiences in the comments section below!

Hello!

Click one of our representatives below to chat on Telegram or send us an email to [email protected]

How can I help you?