How to create and apply coupon in WooCommerce programmatically
Do you want to create coupons and add discounts to 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 discount 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 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 add WooCommerce coupons in different ways:
- Create WooCommerce coupons
- Apply coupon to:
- All products
- Specific products by ID
- The subtotal cart value
- 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 WooCommerce feature you can easily create them in a few clicks.
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. 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.
If you want more details on how to create and set up coupons in WooCommerce, you can check out this step-by-step guide.
Now you know how to create coupons in WooCommerce. Let’s have a look at how to apply them.
2.1) Apply coupon programmatically 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 WooCommerce 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 the 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 adding discounts based on the products, you want to apply a coupon in WooCommerce when customers spend more than $50 in your store. 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. 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 programmatically only when there’s a minimum number of products in the cart. For example, let’s say you want to add a discount when customers 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 applying a discount when shoppers buy 4 or more products 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 is stored. This allows you to have a solid conditional that will add or remove the coupon only when is required. 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 WooCommerce object instances we used in all the above scripts, plus some others that might be useful when you want to add discounts programmatically:
- 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.
Bonus: How to automatically apply a coupon in WooCommerce with a plugin
In this section, we’ll show you how to automatically apply coupons using coupon URLs. The great advantage is that customers don’t need to remember the code so you can directly send it via your newsletter or social media. When users click on the link, they’ll automatically get the discount applied. These coupons are an excellent option to boost your sales during special dates such as Black Friday or Christmas or when you offer flash sales on your store.
Auto-apply coupons with Advanced Coupons for WooCommerce
For this, we’ll use a free plugin called Advanced Coupons for WooCommerce that you can download from the WordPress repository.
- First, install and activate the plugin.
- Then, in your WordPress dashboard, go to WooCommerce > Coupons to create your coupon link. Depending on the WooCommerce version you use, you may have to go to Marketing > Coupons. Press Add coupon.
- In the next screen, name your coupon and a description (optional). Then enter the coupon’s details in the Coupon Data section. You need to choose the type of discount (percentage, fixed cart, or fixed product) and the amount of the discount. Note that the amount will be a percentage or a fixed amount depending on the type of discount you choose. Additionally, you can choose an expiry date and connect the discount to an affiliate account.
- Under the Usage Restrictions tab, you can set restrictions for your coupon. For example, you can limit the minimum or maximum spend, limit the discount for certain products, and so on. On top of that, under Usage limits, you can set a limit to the number of times the coupon can be used and limit the usage per user. NOTE: We recommend you limit the usage per user so they can only use it once.
- After that, go to the URL Coupons section and enter your coupon details. Select an URL where customers will be redirected and create a success message. You’ll see that a coupon URL will be automatically generated. However, if you want to customize it, you can use the Code URL Override box.
- Finally, press Publish and that’s it!
Once you create your coupon URL, promote it using your newsletter and social media to boost your sales!
Extra: How to display the form to enter coupon code by default
Finally, let’s see how to display the form to enter coupon codes by default to make it more noticeable. To do this, you can override the checkout/form-coupon.php template in your child theme and remove style=display:none from the line of code below:
<form class="checkout_coupon" method="post" style="display:none">
For more ways to edit WooCommerce coupon code fields check out this guide.
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:
- All the products
- Specific products by ID
- The subtotal cart value
- 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:
- How to edit the WooCommerce shop page via coding?
- WooCommerce add to cart function programmatically
- Add custom fields to the checkout page
Did you use these scripts? Do you have any questions? Let us know in the comments section below!
9 Comments
Add comment Cancel reply
You must be logged in to post a comment.
Great write up. Is there a way to programmatically create coupons?
Thank you. Check out this post for more information on how to add coupons programmatically.
I want within this code snippet to exclude some coupon codes ids that when customer enter the coupon codes the only items that get affected in the cart are only the one that are assigned on the coupon code and the rest items are not set to regular price if they have sales price. Can you help me to fix the issue??
add_action( ‘woocommerce_before_calculate_totals’, ‘add_custom_price’, 10, 1);
function add_custom_price( $cart_object) {
global $woocommerce;
if ( is_admin() && ! defined( ‘DOING_AJAX’ ) )
return;
$coupon = False;
if ($coupons = WC()->cart->get_applied_coupons() == False )
$coupon = False;
else {
foreach ( WC()->cart->get_applied_coupons() as $code ) {
$coupons1 = new WC_Coupon( $code );
if ($coupons1->type == ‘percent_product’ || $coupons1->type == ‘percent’)
$coupon = True;
}
}
if ($coupon == True)
foreach ( $cart_object->get_cart() as $cart_item )
{
$price = $cart_item[‘data’]->regular_price;
$cart_item[‘data’]->set_price( $price );
}
}
Hi there
You will need to adapt the script to meet your needs.
Inside the “$coupon==True” conditional, create a new
if()
conditional to match the required product ID.$product_id = $cart_item['product_id'];
will work inside the loop in order to retrieve product idGreat write up, you can write more post about variable product?
Thank you.
Hi Tien, we’ll try to write more posts about variable products. In the meantime, you can have a look at our guide to add product variations
Hi,
I have a question about this.
I try to add a box on homepage where customer ca exchange their “coupon code”, then tell message “success” or “invalid” or “already use”, then redirect the customer to the product checkout page concerned by the “coupon code”…
this should be displayed on the homepage.
i have try to add this form on my homepage: it’s display the form, but the message “valid”, “success” etc displayed on the “my account page” and not just above the form (on the homepage).
And i search how redirect customer to the product’s code (the code for this specific product) for help customer directly checkout the good product and applicated the coupon automaticly for this specific product.
For trying to make this i have put this code on my functions.php file, declared a shortcode and called it on the homepage:
add_shortcode( ‘COUPONCODE’, ‘display_coupon_field’ );
function display_coupon_field() {
if( isset($_GET[‘coupon’]) && isset($_GET[‘redeem-coupon’]) ){
if( $coupon = esc_attr($_GET[‘coupon’]) ) {
$applied = WC()->cart->apply_coupon($coupon);
} else {
$coupon = false;
}
$success = sprintf( __(‘GOOD! Your CODE COUPON: “%s” is valid!’), $coupon );
$error = __(“Ooops, your coupon is not valid!”);
$message = isset($applied) && $applied ? $success : $error;
}
$output = ‘
Have you a coupon?
‘;
$output .= isset($coupon) ? ‘‘.$message.’‘ : ”;
return $output . ”;
}
//usage
//Usage: [COUPONCODE] or in Php code echo do_shortcode(“[COUPONCODE]”);
Please, can you help me with this? is it possible? how make it works?
Thanks in advance
Hey Jemo !
Are you getting some error when trying your code?
Because shortcode is not on a WC page, I believe that it won’t work if you don’t call the global WC object “WC()”
Hi,
Thank you for this tutorial. I love bieng able to get things done without a plugin whenever possible.
Is it possible to greate a coupon based on User Role?
Thanks in advance!