WooCommerce: Apply Coupon Programmatically if Product @ Cart

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!

WooCommerce: how to add a coupon programmatically if a product is added to cart
WooCommerce: how to add a coupon programmatically if a product is added to cart

PHP Snippet 1: Apply a Coupon Programmatically if a Product is in the Cart

Notes:

  1. 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)
  2. 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();
}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

62 thoughts on “WooCommerce: Apply Coupon Programmatically if Product @ Cart

  1. 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?

    1. Nevermind! I found what was caused it. Confirm that everything is working good πŸ™‚ Thanks again for your great work and help!

  2. Is there a way to modify this code so that if Coupon Code A is applied, it automatically will apply Coupon Code B?

    1. 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!

  3. I love Businessbloomer. So neat and clean codes.

    Thanks for this awesome work.

    1. Thanks

  4. Thanks for this πŸ™‚

    1. You’re welcome

  5. how can we add coupon only allowed for certain country or shipping zone

    1. 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!

  6. 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.

    1. Thank you!

  7. 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.

    1. 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!

  8. 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

    function wc_exchange_product_by_coupon( $coupon_code ) {
    	// Retrieving the coupon ID
    	$coupon_post_obj = get_page_by_title($coupon_code , OBJECT, 'shop_coupon');
    	$coupon_id       = $coupon_post_obj ->ID;
    	
    	// Get an instance of WC_Coupon object in an array(necessary to use WC_Coupon methods)
    	$coupon = new WC_Coupon($coupon_id);
    	
    	// Check if discount amount is 100% so we exchange the product in the cart for the free product example sanktmarien100
    	$amount = $coupon->get_amount();
    	if ( '100' === $amount ) {
    		//remove other product
    		$product_id_to_remove = 4568 ;
    		$product_cart_id = WC()->cart->generate_cart_id( $product_id_to_remove );
       		$cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );
       		if ( $cart_item_key ){
       			WC()->cart->remove_cart_item( $cart_item_key );
       		}
    	
    		// Add free product
    		$product_id_add = 10965;
    		WC()->cart->add_to_cart( $product_id_add );
    	}
    }
    
    1. Nice!

  9. 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

    1. 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!

  10. 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

    1. 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!

  11. is possible auto add coupon in checkout page ?

    1. Hello Edoardo, what do you mean exactly?

    2. I find this, try with:

      add_action( 'woocommerce_before_cart', 'bbloomer_apply_coupon' );
      add_action( 'woocommerce_before_checkout_form', 'bbloomer_apply_coupon' );
      

      so you use a checkout hook https://docs.woocommerce.com/wc-apidocs/hook-docs.html

      1. Thanks! Following is the final code that I used for auto applying coupon in cart as well as checkout page :

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

        It’s working perfectly fine. Thanks to Business Bloomer & Micheleur.

  12. 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.

    1. 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!

      1. thanks but i already did it with the help of same code.

  13. This is not working with lates WP+WC . Pl check.

    1. Worked for me – the only thing that this snippet doesn’t do is removing the coupon if you remove the product from the Cart

  14. 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!

    1. $request[β€œcoupon_code”] is not part of this snippet

  15. This is useless, when the customer ad something to the cart that is not that ID, she will see an error message

    1. 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

  16. This Snippet is not working with latest Woocommerce version. Pl check . Thanks

    1. Works for me πŸ™‚

  17. 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,

    1. 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

  18. 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

    1. 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

    2. Just replace:

      // this is your product ID
      $autocoupon = array( 745 );

      with:

      // thess are your product IDs
      $autocoupon = array( 745, 746, 747 );

      etc.

  19. How to give a cupan when total any two product in cart availab not for single product

    1. 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

  20. Hi Rodolfo.
    What if I want to use a coupon ID, instead of its name? How can I retrieve coupon id in this case?

    1. 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 πŸ™‚

  21. 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,

    1. 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

  22. 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?

    1. Hey Jisang, thanks so much for your comment! You should make sure the coupon works only for that specific product (in the coupon settings) πŸ™‚

  23. 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?

    add_action( 'woocommerce_before_cart', 'bbloomer_apply_matched_coupons' );
     
    function bbloomer_apply_matched_coupons() {
        global $woocommerce;
     
        $coupon_code = 'SPANISH14'; 
    
        if (  $_product->variation_id == 9552 ) return;
        if ( $woocommerce->cart->has_discount( $coupon_code )) return;
     
        foreach ($woocommerce->cart->cart_contents as $key => $values ) {
     
        // this is your product ID
        $autocoupon = array(8567);
        if(in_array($values['product_id'],$autocoupon)){    
         
            $woocommerce->cart->add_discount( $coupon_code );
            wc_print_notices();
        }
        }
     
    }
    
    1. Hey BillyBoy, thanks for your comment! Sorry but I can’t offer custom troubleshooting here via the blog – thanks a lot for your understanding πŸ™‚

  24. Hi

    How to extend functionality of this snippet to apply coupon when two products (different IDs) are in the cart?

    1. 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!

  25. 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

    1. 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

  26. Great tip thank you so much.

    Is there any way I can apply the coupon to the first purchase that new member does?

    Thank

    1. 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 πŸ™‚

      1. 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?

        1. 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!

  27. 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.

    1. 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

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

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