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        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WC 3.8
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
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->add_discount( $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        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WC 3.8
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
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->add_discount( $coupon_code );
    wc_print_notices();
}

Where to add this snippet?

You can place PHP snippets at the bottom of your child theme functions.php file (before "?>" if you have it). CSS, on the other hand, goes in your child theme style.css file. Make sure you know what you are doing when editing such files - if you need more guidance, please take a look at my free video tutorial "Where to Place WooCommerce Customization?"

Does this snippet (still) work?

Please let me know in the comments if everything worked as expected. I would be happy to revise the snippet if you report otherwise (please provide screenshots). I have tested this code with Storefront theme, the WooCommerce version listed above and a WordPress-friendly hosting on PHP 7+.

If you think this code saved you time & money, please join other Business Bloomer supporters and avail of 365 days of WooCommerce benefits. Thank you in advance :)

Need Help with WooCommerce Customization?

Check out these free video tutorials. You can start learning how to customize WooCommerce without unnecessary plugins. Watch me code and learn by example!

  • how-to-edit-woocommerce-with-php-snippets
  • woocommerce-hooks-add_action-list-visual
  • woocommerce-customize-single-product-page-PHP

Rodolfo Melogli

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as a 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.

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

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

  2. is possible auto add coupon in checkout page ?

    1. Hello Edoardo, what do you mean exactly?

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

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

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

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

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

    1. Works for me ๐Ÿ™‚

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

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

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

  11. 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 ๐Ÿ™‚

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

  13. 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) ๐Ÿ™‚

  14. 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 ๐Ÿ™‚

  15. 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/bloomer-armada/, and the $9/โ‚ฌ9 would definitely cover your request. Let me know and thanks a lot for your understanding!

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

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

  18. 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? Support? Leave your Comment Now!
_____

If you are writing code, please wrap it between: [php]code_here[/php]. Failure to complying with this (as well as going off topic) will result in comment deletion. You should expect a reply in about a week - this is a popular blog but I need to get paid work done first. Please consider joining #BloomerArmada to ask me 1-to-1 WooCommerce questions. Thank you :)

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