Posted on

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

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

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


/**
 * @snippet       How to Apply a Coupon Programmatically if Product ID @ Cart - WooCommerce
 * @how-to        Watch tutorial @ https://businessbloomer.com/?p=19055
 * @sourcecode    https://businessbloomer.com/?p=516
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.5.1
 */

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 Alternative: Apply a Coupon Programmatically for ALL Products


/**
 * @snippet       How to Apply a Coupon Programmatically - WooCommerce
 * @how-to        Watch tutorial @ https://businessbloomer.com/?p=19055
 * @sourcecode    https://businessbloomer.com/?p=516
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.5.1
 */

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 code?

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 delicate files - if you need more guidance, please take a look at my free WooCommerce Customization video tutorial.

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?

Check out these free videos, tutorials and tips!

  • how-to-edit-woocommerce-with-php-snippets
  • woocommerce-hooks-add_action-list-visual
  • woocommerce-customize-single-product-page-PHP
  • woocommerce-customize-shop-page-PHP
  • woocommerce-advanced-customization
  • how-to-edit-woocommerce-cart
  • woocommerce-customize-checkout-page-PHP
  • woocommerce-email-customization
  • woocommerce-conditional-logic

Rodolfo Melogli

Author, WooCommerce expert, WordCamp speaker and Internet marketer, Rodolfo Melogli has worked as a WooCommerce freelancer since 2011. He helps entrepreneurs and developers overcome their WooCommerce nightmares :) Rodolfo is the organiser of WordCamp Dublin, the Dublin WooCommerce Meetup, the Dublin Ecommerce Meetup and the Dublin WordPress Meetup. He enjoys interacting with people, travelling and chasing tennis & soccer balls. Of course, he loves pizza too.

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

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

    1. Works for me πŸ™‚

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

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

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

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

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

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

  8. […] I’ve always looked for products in the Cart by “looping” through the Cart with a foreach (here, for example: Apply a Coupon Programmatically if a Product is in the Cart). […]

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

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

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

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

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

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

  13. 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're writing code, please wrap it between: [php] code_here [/php]

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.