Users can manually enter a coupon code, refresh the Cart and see their discount apply… or you can do that automatically (or “programmatically” as we say in the dark web) when a user adds a product to the WooCommerce Cart π
All you’ve got to do is creating a coupon, and then a PHP function will do the whole work. Automation is the best thing in the world!
PHP Snippet 1: Apply a Coupon Programmatically if a Product is in the Cart
Notes:
- Create a coupon code that you want to apply once a certain product is added to cart (go to WooCommerce / Coupons / Add New and decide your coupon code. For example “freeweek”, which is the coupon code we will use later in the PHP snippet)
- Identify your product ID (go to WordPress / Products and hover onto the product you want to use the coupon with. Whatever ID shows in the URL bar, take a note. In our example, we will target product ID = “745”)
/**
* @snippet Apply a Coupon Programmatically if Product @ Cart - WooCommerce
* @how-to businessbloomer.com/woocommerce-customization
* @author Rodolfo Melogli, Business Bloomer
* @compatible WC 4.1
* @community https://businessbloomer.com/club/
*/
add_action( 'woocommerce_before_cart', 'bbloomer_apply_matched_coupons' );
function bbloomer_apply_matched_coupons() {
$coupon_code = 'freeweek';
if ( WC()->cart->has_discount( $coupon_code ) ) return;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// this is your product ID
$autocoupon = array( 745 );
if ( in_array( $cart_item['product_id'], $autocoupon ) ) {
WC()->cart->apply_coupon( $coupon_code );
wc_print_notices();
}
}
}
PHP Snippet 2: Apply a Coupon Programmatically for ALL Products
/**
* @snippet How to Apply a Coupon Programmatically - WooCommerce Cart
* @how-to businessbloomer.com/woocommerce-customization
* @author Rodolfo Melogli, Business Bloomer
* @compatible WC 4.1
* @community https://businessbloomer.com/club/
*/
add_action( 'woocommerce_before_cart', 'bbloomer_apply_coupon' );
function bbloomer_apply_coupon() {
$coupon_code = 'freeweek';
if ( WC()->cart->has_discount( $coupon_code ) ) return;
WC()->cart->apply_coupon( $coupon_code );
wc_print_notices();
}
Hi, thank you for this code. It still works, but found some edge case with WC 6.1.1. When product from the IDs array is added, the coupon code is applied. But if I add any other products after the one of array, the coupon code is not applied. I mean that the product from the array must be the only one in the cart or the last one added. Otherwise the coupon code does not apply. Any ideas?
Nevermind! I found what was caused it. Confirm that everything is working good π Thanks again for your great work and help!
Great!
Is there a way to modify this code so that if Coupon Code A is applied, it automatically will apply Coupon Code B?
Hi Marc, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
I love Businessbloomer. So neat and clean codes.
Thanks for this awesome work.
Thanks
Thanks for this π
You’re welcome
how can we add coupon only allowed for certain country or shipping zone
Faheem, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
New WC methods as outlined here:
https://docs.woocommerce.com/wc-apidocs/class-WC_Cart.html
//add a coupon
WC()->cart->apply_coupon( $coupon_code );
//remove a coupon
WC()->cart->remove_coupon( $coupon_code );
Cheers,
C.
Thank you!
How can I apply the coupon code using the URL parameters?
basically I want to create a special discount code to send in an email, on click, the product should be added to cart, with coupon applied and user on the checkout page. Want to avoid using a plugin.
Hey there, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
Thanks for the snippet I created something based on that and based on some other articles, the strange thing is that I needed to clear the cart before I added the other product, if I added the free product first and removed the other product at the end the cart was always empty.
Nevertheless maybe it is useful for somebody, I check for a certain coupon amount (100%) and then I removed the current product and added the free product which has some small limitations because I have coupled woocommerce with a membership site.
Best regards
Johannes
Nice!
Can I do it using link?
like https://my-site.com/?add-to-cart=19741?coupon=my-coupon?
I want people get the coupon if they click link
Hi Rubb, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
Hello,
It’s possible to change formatting of this string? to add percent coupon value near of promo code, by example?
like “Couponlabel “mycouponcode” (10%) ………….. -$13.20 [Remove]”
Thanks for your help!
Cheers
Hello Nick, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
is possible auto add coupon in checkout page ?
Hello Edoardo, what do you mean exactly?
I find this, try with:
so you use a checkout hook https://docs.woocommerce.com/wc-apidocs/hook-docs.html
Thanks! Following is the final code that I used for auto applying coupon in cart as well as checkout page :
It’s working perfectly fine. Thanks to Business Bloomer & Micheleur.
Cool!
Can this be done at checkout page? I have a buy now page setup on the single product page, thus customer directly lands at checkout page instead of the cart page. What should I do so that this code applies to a customer who lands directly to checkout and not cart->checkout.
Hi Parth, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
thanks but i already did it with the help of same code.
This is not working with lates WP+WC . Pl check.
Worked for me – the only thing that this snippet doesn’t do is removing the coupon if you remove the product from the Cart
Hi,
I am new to woocommerce platform. I am integrating its API to mobile app.
1. From your code, when I add this function βwc_print_notices();β to my php file it returns βunexpectedcart->has_discount( $request[βcoupon_codeβ] ) )
Any help will be appreciated!
Thanks!
$request[βcoupon_codeβ] is not part of this snippet
This is useless, when the customer ad something to the cart that is not that ID, she will see an error message
Hello Ricardo, thanks so much for your comment! I just retested this on the latest version of WooCommerce and it still works. Unfortunately this looks like custom troubleshooting work and I cannot help here via the blog comments. Thanks a lot for your understanding! ~R
This Snippet is not working with latest Woocommerce version. Pl check . Thanks
Works for me π
Hi,
Thank you for sharing these interesting topics in Woocommerce. I have a question, please?
I have created custom fields for user registration form and one of the fields is profession it is a drop-down list and of the values is Doctor, So what I want is whenever the user’s profession is Doctor I want the coupon code to add automatically.
Any idea?
Thanks in advance,
Majd, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R
Hey,
Thanks for the great work!
2 questions;
1. How can i add more then 1 id? looking to group a few id’s together which would trigger promo code
2. How can i modify the code so itll allow for many groups / auto coupons?
Much appriciated
Hello Justin, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R
Just replace:
// this is your product ID
$autocoupon = array( 745 );
with:
// thess are your product IDs
$autocoupon = array( 745, 746, 747 );
etc.
How to give a cupan when total any two product in cart availab not for single product
Hello Pallavi, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R
Hi Rodolfo.
What if I want to use a coupon ID, instead of its name? How can I retrieve coupon id in this case?
Hey Alessandro – thanks so much for your comment! You’ll need to study the WooCommerce functions to find that out – I can’t help here via the blog comments. Thank you π
Hello,
I am trying to figure out how to add email notifications when a specific code is applied. In fact, a coupon code will be assigned to sale representative, and we want them to be notified each time their coupon is applied and use.
Thanks,
Hey Stella, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R
Hi, Rodolfo. This article is exactly what I was looking for. I appreciate it. I got lots of clue for the problem I have now. By the way, I found out when we click “remove” button on cart page, total price is not going back to original price. I think it should be back to state which coupon wasn’t applied. Isn’t it?
Hey Jisang, thanks so much for your comment! You should make sure the coupon works only for that specific product (in the coupon settings) π
Hi Rodolfo
Many thanks for your posts on WooCommerce, they’re a great help.
I’m trying to filter the auto apply coupon to a product and a single variation, I’ve tried the following but it still applies to all the other variations of the same product.
Would you know where I’ve gone wrong in the code?
Hey BillyBoy, thanks for your comment! Sorry but I canβt offer custom troubleshooting here via the blog β thanks a lot for your understanding π
Hi
How to extend functionality of this snippet to apply coupon when two products (different IDs) are in the cart?
Hello Jurasjo, thanks for your comment! I’m afraid I can’t help this time – this is custom work and unfortunately I can’t provide premium support to free subscribers. Hope this is ok π
Just for your interest, I just launched https://businessbloomer.com/club/, and the $9/β¬9 would definitely cover your request. Let me know and thanks a lot for your understanding!
Hi, what im a looking for is kind of the reverse of what your doing here, what i want to do is add a product to the cart as a zero value (a gift) if a a certain coupon is applied, i have found and played with a free gift coupon plugin but its very limeted i need to be able to apply a cash value aswell as free give
so say if some uses the coupon : sxmq192m
it will +free gift and -20 from cart total
Brad, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide you with a complementary solution here on the blog. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R
Great tip thank you so much.
Is there any way I can apply the coupon to the first purchase that new member does?
Thank
Hey, thanks for your comment! I’m sure there is a way (there is always a PHP way!)… however this is custom work so I’m afraid I cannot provide you with an answer on the blog. Thanks for your understanding π
I agree, there is always a way. Is there any way to modify your code, so it applies a coupon to all the products instead of one particular product?
Hey KA, thanks for your comment. You can play with the coupon settings, no need to change the PHP. You can pick a coupon code in the PHP that either apply to a single product, a single category, all products, the cart, many product IDs… so just make sure to choose the corect coupon settings and then call that coupon code from the PHP. Hope this helps!
Thanks for this great tip! I have 2 questions: (1) How do I apply the discount to a category as opposed to individual products? and (2) For some reason, the [$woocommerce->show_messages();] code causes a fatal error. If I disable this line, the discount applies correcty. Any idea why? I’d like the message to display.
Thanks for your feedback Patty! Thanks for (2), this is a bug, I’ve fixed the snippet now – you need to use “wc_print_notices();” instead as that other function is deprecated. For (1), unfortunately it’s custom work and I cannot provide this solution on the blog right now. If you would like to get a quote, feel free to go here. Thank you! R