How to Auto Apply a Coupon in WooCommerce (for free)

WooCommerce allows you to create coupons easily, but customers usually don’t know about the coupon, so they leave the cart without purchasing. It can be very frustrating that the customers leave the cart even after a coupon discount

But creating a coupon is useless if they can’t use it or don’t know about it. So one of the easy ways to ensure that they complete the purchase is by automatically applying the coupon code as soon as a customer adds a product to the cart. 

It will encourage them to complete the purchase and increase the customer’s trust as you are willing to give them discounts even if they don’t know about the coupon code. 

In today’s guide, we’ll be doing the same thing. I’ll share the custom code you can copy and paste to your WooCommerce store to auto-apply the coupon.  I’ll also share a few different use cases to help you further. 

So without any further ado, let’s jump into the tutorial.

How to Auto Apply a Coupon in WooCommerce (Using Code)?

Here, I’ll share the code snippets you can use to get the desired results. I’ll share five different scenarios. 

Note: I assume you already created a coupon code to keep this tutorial short and concise. If not, first, you need to create a coupon code by going into the WooCommerce>>Coupons from your WordPress dashboard. 

1. Auto Apply Coupon As Soon As the Product is Added to the Cart

If you want to apply the coupon to the complete cart automatically, the following code will help you. 

1.1. Code to Auto Apply Coupon to Cart

The following code snippet will help you to auto-apply the coupon to the complete cart.  Make sure to change the SUMMERDEAL with the coupon you created. 

function woosuite_auto_apply_coupon_to_cart() {
    $coupon_code = '10discount'; //Replace it with your coupon code
    
    if (WC()->cart->has_discount($coupon_code)) {
        return;
    }
    
    if (WC()->cart->apply_coupon(sanitize_text_field($coupon_code))) {
        wc_print_notices();
    } else {
        wc_print_notices();
    }
}
add_action('woocommerce_before_calculate_totals', 'woosuite_auto_apply_coupon_to_cart');

1.2. Understanding the Code (Optional)

Let’s go through the code to give you a clear understanding of each step:

  • The function woosuite_auto_apply_coupon_to_cart() is defined. This function is hooked to the woocommerce_before_calculate_totals action, which is triggered before the cart totals are calculated.
  • The variable $coupon_code is set to the coupon code you want to apply automatically. In this example, it’s set to ’10discount.
  • The code checks if the coupon is already applied to the cart using the has_discount() method. If the coupon is already applied, the function returns and exits without making any further changes.
  • If the coupon is not already applied, the code attempts to apply the coupon to the cart using the apply_coupon() method. The sanitize_text_field() function is used to sanitize the coupon code before applying it.
  • If the coupon is successfully applied, the function calls wc_print_notices() to display success messages. If the coupon fails to apply, it also calls wc_print_notices() to display error messages.
  • Finally, the function is hooked to the woocommerce_before_calculate_totals action using add_action(), which will be executed when the cart totals are calculated.

If you want to learn more about the WooCommerce cart page hooks, please follow the following guide. 

1.3. Paste the Code to Your WooCommerce Store

There are several methods to paste the code to your store, and you can use any of the available methods. Here’s a guide that will tell you how to paste the code to your store. 

For this tutorial, I used the plugin to add the code snippet to my demo store. 

1.4. Final Results

Once you have added the code to your store, let’s test the final results. 

Note: As mentioned earlier, I have already created a coupon code. The coupon code will give a 10% discount on the total cart

Here are the final results that I got after adding a product to my cart. The coupon was applied automatically when I visited the cart page

 2. Auto Apply Coupons For Specific Product IDs

If you want to auto apply the coupon for specific product ids, you can use the following code. It will help you automatically apply the coupon code when the customer adds a specific product to the cart. 

21. Code to Auto Apply Coupons For Specific Product IDs

Here’s the code to help you to auto-apply the coupon code for specific product ids. 

Note: Do not forget to replace the values for $product_ids and the $coupon_code. 

function woosuite_auto_apply_coupon_to_specific_products() {
    // Specify the coupon code to be automatically applied
    $coupon_code = '10discount';

    // Specify the product IDs for which the coupon should be applied
    $product_ids = array(1906, 1907);

    // Check if any of the specified product IDs are in the cart
    $apply_coupon = false;
    foreach (WC()->cart->get_cart() as $cart_item) {
        if (in_array($cart_item['product_id'], $product_ids)) {
            $apply_coupon = true;
            break;
        }
    }

    // Check if the coupon is already applied
    if (WC()->cart->has_discount($coupon_code)) {
        return; // Exit the function if the coupon is already applied
    }

    // Apply the coupon to the cart if the product IDs match
    if ($apply_coupon) {
        // Check if the coupon is valid and apply it to the cart
        if (WC()->cart->apply_coupon(sanitize_text_field($coupon_code))) {
            // Coupon applied successfully
            wc_print_notices(); // Display a success message
        } else {
            // Coupon failed to apply
            wc_print_notices(); // Display an error message
        }
    }
}
add_action('woocommerce_before_calculate_totals', 'woosuite_auto_apply_coupon_to_specific_products');

2.2. Understanding the Code (Optional)

Let’s go through the code to give you a clear understanding of each step:

  • The function woosuite_auto_apply_coupon_to_specific_products() is hooked to the woocommerce_before_calculate_totals action, which is triggered before calculating the cart totals.
  • The coupon code to be automatically applied is specified as $coupon_code, and the product IDs for which the coupon should be applied are specified as an array in $product_ids.
  • The code checks if any specified product IDs are in the cart. If at least one of the product IDs is found, the variable $apply_coupon is set to true.
  • It then checks if the coupon code is already applied to the cart. If the coupon is already applied, the function exits.
  • If $apply_coupon is true, indicating that the product IDs match, the code attempts to apply the coupon code to the cart using the apply_coupon() method.
  • If the coupon is applied successfully, it displays a success message using wc_print_notices(). If the coupon fails to apply, it displays an error message.
  • Finally, the function is hooked to the woocommerce_before_calculate_totals action using add_action(), which will be executed when the cart totals are calculated.

2.3. Final Results

Once you have added the above code snippet to your store, you can test it. I added a random product to my cart, and the coupon wasn’t applied because the product id didn’t match. 

After that, I added the product with the specified id to my cart, and now when I revisited my cart page, the coupon code was applied automatically. 

3. Auto Apply Coupon When Customers Spend More Than $100

Another scenario is to apply a coupon if the customer is spending more than $100 on your store. 

3.1. Code to Auto Apply Coupon When Customers Spend More Than $100

The following is the code to auto-apply a coupon if a customer spends more than $100. You can change the spending limit depending on your requirements. 

// Hook into the "woocommerce_before_calculate_totals" action
add_action('woocommerce_before_calculate_totals', 'woosuite_apply_coupon_based_on_cart_total');

function woosuite_apply_coupon_based_on_cart_total() {
    $coupon_code = '50discount'; // Replace with your actual coupon code
    $minimum_total = 100; // Minimum cart total to apply the coupon

    if (WC()->cart->total >= $minimum_total) {
        // Check if the coupon is already applied
        if (WC()->cart->has_discount($coupon_code)) {
            return; // Coupon is already applied
        }

        // Apply the coupon
        WC()->cart->apply_coupon($coupon_code);
    }
}

3.2. Understanding the Code

Here’s a brief explanation of the code:

  • The code uses the woocommerce_before_calculate_totals action hook, which is triggered before calculating the cart totals.
  • The function woosuite_apply_coupon_based_on_cart_total() is defined to be executed when the woocommerce_before_calculate_totals action is triggered.
  • The coupon code you want to apply is specified as ‘YOUR_COUPON_CODE’. You need to replace it with the coupon code you want.
  • The minimum cart total required to apply the coupon is set as $minimum_total, currently set to 100. You can adjust this value to your desired minimum total.
  • Inside the function, it checks if the cart total (WC()->cart->total) is greater than or equal to the minimum total specified.
  • If the cart total meets the criteria, it checks if the coupon is already applied using the has_discount() method. If the coupon is already applied, the function exits.
  • If the coupon is not already applied, it applies the coupon code using the apply_coupon() method.

3.3. Final Results

Once you have added the code to your store, let’s test the final results. To test it, I first added a product to my cart that was worth less than $100, and no coupon was applied. 

After that, I increased the product quantity so the cart total was greater than $100, and now the coupon was applied automatically. 

4. Auto Apply Coupon Depending on the Number of Products in the Cart

The next scenario could be that you want to auto-apply a coupon as a user adds a specified number of products to the cart. You can minimum product quantity required to apply the coupon as you want. 

4.1. Code to Auto Apply Coupon Depending on the Number of Products in the Cart

The following code will help you to auto-apply a coupon code depending on the number of products a user has added to the cart. 

// Hook into the "woocommerce_before_calculate_totals" action
add_action('woocommerce_before_calculate_totals', 'woosuite_apply_coupon_based_on_product_count');

function woosuite_apply_coupon_based_on_product_count() {
    $coupon_code = '50discount'; // Replace with your actual coupon code
    $minimum_product_count = 5; // Minimum product count to apply the coupon

    $product_count = WC()->cart->get_cart_contents_count();

    if ($product_count >= $minimum_product_count) {
        // Check if the coupon is already applied
        if (WC()->cart->has_discount($coupon_code)) {
            return; // Coupon is already applied
        }

        // Apply the coupon
        WC()->cart->apply_coupon($coupon_code);
    }
}

4.2. Understanding the Code

Here’s a brief explanation of the code for your better understanding:

  • The code hooks into the woocommerce_before_calculate_totals action, which is triggered before calculating the cart totals.
  • The function woosuite_apply_coupon_based_on_product_count() is defined to be executed when the woocommerce_before_calculate_totals action is triggered.
  • The coupon code you want to apply is specified as ‘YOUR_COUPON_CODE’. Replace it with the actual coupon code you want to use.
  • The minimum product count required to apply the coupon is set as $minimum_product_count, currently set to 5. You can adjust this value to your desired minimum product count.
  • Inside the function, it calculates the number of products in the cart using WC()->cart->get_cart_contents_count().
  • If the product count in the cart meets or exceeds the minimum product count specified, it checks if the coupon is already applied using the has_discount() method. If the coupon is already applied, the function exits.
  • If the coupon is not already applied and the product count meets the criteria, it applies the coupon code to the cart using the apply_coupon() method.

4.3. Final Results

After pasting the code to your WooCommerce store, we next need to test if it is working. I added three products to my cart to test it and checked if the coupon was auto-applied. 

But it wasn’t. So, I added two more products to my cart, and this time, when I checked the cart or visited the checkout, the coupon was automatically applied. 

5. Auto Apply Coupon Using WooCommerce Coupon Code URL

Sometimes, the users have left the cart without purchasing anything from your store. In that case, you can email them the coupon URL. When they click the URL, they’ll be redirected to your store, and the coupon code will be applied automatically. 

It may encourage them to complete the purchase they left. 

However, if you are not experienced with WordPress and WooCommerce code, I do not recommend using this method as it may get complicated and cause issues

5.1. Code to Auto Apply Coupon When User Clicks the Coupon URL

The following is the code you need to copy to auto-apply the coupon using the coupon URL. 

// Hook into the "init" action
add_action('init', 'woosuite_auto_apply_coupon_code_from_url');

function woosuite_auto_apply_coupon_code_from_url() {
	$coupon_code = '50discount';
    if (isset($_GET['apply_coupon'])) {
        $coupon_code = sanitize_text_field($_GET['apply_coupon']);

        // Check if the coupon code is valid
        if (WC()->cart->has_discount($coupon_code)) {
            return; // Coupon is already applied
        }

        // Apply the coupon
        WC()->cart->apply_coupon($coupon_code);
    }
}

5.2. Understanding the Code

Here’s a brief explanation to help you understand the code:

  • The code hooks into the init action using add_action(‘init’, ‘auto_apply_coupon_code_from_url’). This ensures that the woosuite_auto_apply_coupon_code_from_url() function is executed early in the WordPress loading process.
  • The function woosuite_auto_apply_coupon_code_from_url() is defined to be executed when the init action is triggered.
  • The default coupon code to be applied is set as ’50discount’ using the $coupon_code variable.
  • The code checks if the apply_coupon parameter exists in the URL query string using isset($_GET[‘apply_coupon’]).
  • If the apply_coupon parameter is present, it retrieves the coupon code from $_GET[‘apply_coupon’] using sanitize_text_field() to sanitize the value and store it in the $coupon_code variable.
  • Next, it checks if the coupon is already applied to the cart using the has_discount() method. If the coupon is already applied, the function exits.
  • If the coupon is not already applied, it proceeds to apply the coupon code to the cart using WC()->cart->apply_coupon($coupon_code).

Note: Remember to test each code snippet thoroughly on a development or staging environment before applying it to a production store.

5.3. Final Results

After pasting the code snippet to your site, we need to test it. To test it, you can visit the coupon URL, which will be something like this:

https://example.com/?apply_coupon=YOUR_COUPON_CODE

Ensure to replace the example.com with your domain name and YOUR_COUPON_CODE with the coupon code that you want to apply. 

When a customer you’ll click the link, the coupon will be applied automatically to the cart. 

Conclusion

That’s it for today’s article. 

I hope this article was helpful to you and you were able to learn something from it. If you are a store owner, using the above code snippets can help you greatly to increase sales and customers. 

If you find working with custom code snippets challenging, you can use the Dynamic Pricing & Discount Rules plugin to create and apply different discounts and coupons. 

Brian
Brian

Welcome to the AovUp blog, where we discuss all things WooCommerce. I hope we can help you achieve something today...

Leave a Reply

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

We – and our partners – use cookies to deliver our services and to show you ads. By using our website, you agree to the use of cookies as described in our Cookie Policy