WooCommerce: How to apply discount coupon automatically

Step 1: Create a coupon (http://docs.woothemes.com/document/coupon-management/)

 

Step 2: Add this code in your theme function.php

add_action( 'woocommerce_before_cart', 'apply_matched_coupons' );

function apply_matched_coupons() {
    global $woocommerce;

    $coupon_code = '10percent'; // your coupon code here

    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

    if ( $woocommerce->cart->cart_contents_total >= 500 ) {
        $woocommerce->cart->add_discount( $coupon_code );
        $woocommerce->show_messages();
    }

}

 

Advertisements

94 thoughts on “WooCommerce: How to apply discount coupon automatically

  1. hello
    Thank you very much for your post, helped me a lot.
    I tried to modify your code to apply the coupon, with the weight of a product and not just a set and my code did not work
    I would like to apply a discount when people buy 100 lb of product1, but if you buy other products (1 2 3 4) and weighing 100 lb, the coupon does not apply.
    If you buy 100 lb of product1 + 50 lb of product (2 3 4 5) to apply the coupon.
    I want is the condition to apply the coupon is or 100 lb of product 1 (I could use money $ 100, alternative to weight)
    Any idea that can help me.
    thank you very much

  2. Hello
    I’m sorry I did not and found his email to write
    Thank you very much for your help
    In my small shop I am creating I have 5 categories and over 100 products.
    When customers purchase a minimum amount of product, 100 lb or $ 200, is indifferent, applied a discount
    To make it easy products No. 15 and No. 10 are the minimum requirements to apply discount coupon
    The other product not apply a discount coupon
    If the customer purchases the minimum amount of product # 15 or # 10 and also buy other product applies the discount coupon
    Examples

    A customer buys Product 100 lb # 10 category A, you apply a discount coupon $ 30 and free shipping.

    A customer buys product 200 lb # 15 category B, we apply a discount coupon $ 40 and free shipping.
    Category A and B because they are all products in the same category.

    A customer buys 50 lb product category No 10 A, not apply a discount coupon.
    A customer buys 50 lb product category b No. 15 does not apply a coupon discount.

    A customer buys Product 100 lb # 10 category A + 50 lb of product No. 30 category A, you apply a discount coupon $ 30 and free shipping.

    A customer buys 100 lb product category No 30 A + 50 lb of product # 10 category A, not apply a discount coupon.

    This part is not if you could make
    A customer buys 70 lb Product # 10 category A, 50% discount on shipping charges

  3. Hi,,

    Your code help me a lot when I want to apply automatic discount with coupon for customers. But sometimes when i get order from customers, why the coupon did not apply automatically? althoung in many cases, it runs well.. So, is there some condition causing coupon cannot apply automatically? Because i didn’t found it why?

      1. function apply_matched_coupons() {
        global $woocommerce;

        $coupon_code = ‘OKTOBER5’; // your coupon code here

        if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

        //if ( $woocommerce->cart->cart_contents_total >= 500 ) {
        $woocommerce->cart->add_discount( $coupon_code );
        $woocommerce->show_messages();
        //}

        }

        This is the code i used, sometimes run well, but sometimes not..

    1. Hi,

      The code is perfect, when your customers go to checkout via the cart. The problem occurs when they go directly to checkout page.
      Please try to add this addition line:

      add_action( ‘woocommerce_before_checkout_form’, ‘apply_matched_coupons’ );

      1. Best Pinaki,

        i have 2 discount coupon. discount 1 and discount 2. I add the discount 1 coupon to my functions.php that works. but where do i have to add discount 2 coupon. If i add it to my functions.php it gives me a error.

        Can you please give me an example. it doesnt work. do i have to add the second discount also in the function.php? If i try that it gives me a error.

        I hope you can help me.

  4. Hello Pinaki, can you help me with the following issue?

    I would like to apply a discount to a specific product ONLY if the customer is purchasing OTHER items besides this item. However if a customer is only purchasing this item, then do not apply a discount.

    For example:

    If ‘special item’ is the only item in the cart, do not apply the discount.
    If ‘special item’ is NOT the only item in the cart, yes apply the discount.

    Can you help?

    Best,
    Randy

    1. I can give you a idea, I can not give you the full code, I am too busy. If you wait for one or two days then i can give you the code for that.

      Inside the if condition block you can get the items id from cart. with that you can do this easily. You can get the cart items id from this $woocommerce->cart.

      Thanks
      Pinaki

      1. Hi Pinaki, thanks for your response.

        Since my patience skills are far more advanced than my developer skills, I am more than happy to wait for the full code. 🙂 I am happy to wait one or two days…

        Thank you!

      2. That reminds me… I wanted to also have a message on the shopping cart page with the following logic:

        If specific product (Item#:1) is in cart with zero other products, display message that says “This Item#1 can be free if you purchase any other items from our shop.”

        If specific product (Item#:1) is in cart with one or more other products, display message that says “Your Item#1 is now free! At our website, you can always get Item#1 free with the purchase of any of the products from our shop”

        Thank you so much Pinaki!

        Randy

    2. Here is the code

      add_action( ‘woocommerce_before_cart’, ‘apply_matched_coupons’ );
      add_action( ‘woocommerce_before_checkout_form’, ‘apply_matched_coupons’ );

      function apply_matched_coupons() {
      global $woocommerce;

      $coupon_code = ’10percent’; // your coupon code here

      if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

      $cartitems = $woocommerce->cart->get_cart();
      $itemcount = count( $cartitems );
      if($itemcount>1){
      foreach($cartitems as $cartitem){
      $productid = $cartitem[product_id];
      $specialitemid = ’500′; //// your special item id here
      if($productid == $specialitemid)
      {

      $woocommerce->cart->add_discount( $coupon_code );
      $woocommerce->show_messages();

      }
      }
      }

      }

      1. Hello Randy!!

        Really strange! I send you this code after testing. It is working fine. Did you put the product id of the special product current? Send me the code which you are using?

        Best
        Pinaki

      2. Hi Pinaki,

        Yes, I have no idea why it won’t work… Here is the code:

        add_action( ‘woocommerce_before_cart’, ‘apply_matched_coupons’ );
        add_action( ‘woocommerce_before_checkout_form’, ‘apply_matched_coupons’ );

        function apply_matched_coupons() {
        global $woocommerce;

        $coupon_code = ’fmpwp100%’; // your coupon code here

        if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

        $cartitems = $woocommerce->cart->get_cart();
        $itemcount = count( $cartitems );
        if($itemcount>1){
        foreach($cartitems as $cartitem){
        $productid = $cartitem[product_id];
        $specialitemid = ’8766′; //// your special item id here
        if($productid == $specialitemid)
        {

        $woocommerce->cart->add_discount( $coupon_code );
        $woocommerce->show_messages();

        }
        }
        }

        }

        Let me know if this is still correct?

        Thank you!

      3. Hello Randy!

        Please check the website now. All are working fine. Please clear browser cache before test. You can test as gust or any other user account, because admin account has some cache problem.

        Cheer up
        Pinaki

      4. Hello Randy!

        Please check the website now. All are working fine. Please clear browser cache before test. You can test as gust or any other user account, because admin account has some cache problem.

        Cheer up
        Pinaki

    1. Hi Pinaki, do you have the full code yet by chance?

      I’m sorry to bother you as I know you are busy.

      Please let me know if a monetary incentive would help to prioritize this.

      I’m happy to pay for the working code if that helps you.

      Best,
      Randy

      1. Here is the code

        add_action( ‘woocommerce_before_cart’, ‘apply_matched_coupons’ );
        add_action( ‘woocommerce_before_checkout_form’, ‘apply_matched_coupons’ );

        function apply_matched_coupons() {
        global $woocommerce;

        $coupon_code = ’10percent’; // your coupon code here

        if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

        $cartitems = $woocommerce->cart->get_cart();
        $itemcount = count( $cartitems );
        if($itemcount>1){
        foreach($cartitems as $cartitem){
        $productid = $cartitem[product_id];
        $specialitemid = ‘500’; //// your special item id here
        if($productid == $specialitemid)
        {

        $woocommerce->cart->add_discount( $coupon_code );
        $woocommerce->show_messages();

        }
        }
        }

        }

  5. Any way to hide the “coupon is not valid” notification that pops up if the user does not yet have the appropriate items in the cart yet? My discount code works when the user has 2 specific items in their cart, but if a user has only one, the cart constantly says “coupon is not valid.”

      1. the code i have implemented is the same as you have posted above. I understand that it functions if you have $500 in the cart; mine needs an: if product #2040 and product #3338 are in the cart, apply the discount code.

        function apply_matched_coupons() {
        global $woocommerce;

        $coupon_code = ‘pb70-bundle′; // your coupon code here

        if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

        //if ( $woocommerce->cart->cart_contents_total >= 500 ) {
        $woocommerce->cart->add_discount( $coupon_code );
        $woocommerce->show_messages();
        //}

        }

      2. Elle!!

        You need to do a small tweaks in this code. I think this is easy for you.

        add_action( ‘woocommerce_before_cart’, ‘apply_matched_coupons’ );
        add_action( ‘woocommerce_before_checkout_form’, ‘apply_matched_coupons’ );

        function apply_matched_coupons() {
        global $woocommerce;

        $coupon_code = ’10percent’; // your coupon code here

        if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

        $cartitems = $woocommerce->cart->get_cart();
        $itemcount = count( $cartitems );
        if($itemcount>1){
        foreach($cartitems as $cartitem){
        $productid = $cartitem[product_id];
        $specialitemid = ’500′; //// your special item id here
        if($productid == $specialitemid)
        {

        $woocommerce->cart->add_discount( $coupon_code );
        $woocommerce->show_messages();

        }
        }
        }

        }

        Best of luck 🙂

        Pinaki

  6. Hi Pinaki, one of the ninja’s from WooThemes (Mike Jolley) pointed me to your site/code to automatically apply a discount coupon. I need something like you stated in yout blog.
    When a customer orders from certain location (postcode),he should be granted the discount from the coupon. Mike suggested to use your code but revoke the coupon when the customer is not in the postcode list I place in the postcode box under local delivery.I do understand php but I have never used the WooCommerce API/Callbacks. Would you be so kind to help me with the code?
    TIA!
    Egbert Jan, NL

  7. Hi Pinaki,
    Sorry to open an old thread and hoping you can help me out.
    I’ve added code similar to yours on my wordpress site and can get the coupons to apply automatically, however this does not work if I have any excluded products or product categories.
    Do you know how I can tweak this code so that it applies the coupons automatically even when I have excluded products/procuct categories?
    Here’s my existing code:

    add_action( ‘woocommerce_before_cart’, ‘apply_matched_coupons’ );

    function apply_matched_coupons() {
    global $woocommerce;

    $coupon_code = ‘15% off’;

    $woocommerce->cart->remove_coupons();

    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

    if ( $woocommerce->cart->cart_contents_total >= 200 ) {
    $woocommerce->cart->add_discount( $coupon_code );
    $woocommerce->show_messages();
    }

    $coupon_code = ‘10% off’;

    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

    if ( $woocommerce->cart->cart_contents_total >= 100 && $woocommerce->cart->cart_contents_total cart->add_discount( $coupon_code );
    $woocommerce->show_messages();
    }

    }

    Any assistance would be really appreciated!!
    Many thanks,
    Simon

  8. Hi Pinaki,
    Great to see such a dedicated & helpful person on the web 🙂
    I’ve applied code to make two discount coupons (10% off & 20% off) work in WooCommerce).
    However there are some issues with this I was hoping you knew how to work around?
    Firstly I’d like to have that if someone adds an alternative coupon that these two coupons become inactive. This will avoid a supplier with their own discount also receiving these generic discounts.
    Secondly, these coupons don’t seem to work when I add product or category exclusions to them. We have some product packs that need to be excluded, however when I do this the ‘coupon is not valid’ error message occurs.
    Here’s the current code which I’ve included in the functions.php file:

    add_action( ‘woocommerce_before_cart’, ‘apply_matched_coupons’ );

    function apply_matched_coupons() {
    global $woocommerce;

    $coupon_code = ‘15% off’;

    $woocommerce->cart->remove_coupons();

    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

    if ( $woocommerce->cart->cart_contents_total >= 200 ) {
    $woocommerce->cart->add_discount( $coupon_code );
    $woocommerce->show_messages();
    }

    $coupon_code = ‘10% off’;

    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

    if ( $woocommerce->cart->cart_contents_total >= 100 && $woocommerce->cart->cart_contents_total cart->add_discount( $coupon_code );
    $woocommerce->show_messages();
    }

    }

    Any advice and assistance would be greatly appreciated.

    Thanks for your time,
    Simon

  9. I’m also needing to do this exact thing too. So 10% off your cart from £200 to £399, 12.5% off your cart from £400 to £599 and 15% off the cart for £600 and upwards.

    I’ve kind of hacked around your code a bit (very badly, sorry) and almost got it working but some professional input would be much appreciated Pinaki!

    Here’s my code:

    add_action( ‘woocommerce_before_cart’, ‘apply_matched_coupons’ );

    function apply_matched_coupons() {
    global $woocommerce;

    $coupon_code10 = ’10percent’; // your coupon code here
    $coupon_code12 = ‘12.5percent’; // your coupon code here
    $coupon_code15 = ’15percent’; // your coupon code here

    if ( $woocommerce->cart->cart_contents_total >= 200 ) {
    $woocommerce->cart->add_discount( $coupon_code10 );
    }
    if ( $woocommerce->cart->cart_contents_total >= 400 ) {
    $woocommerce->cart->add_discount( $coupon_code12 );
    }
    if ( $woocommerce->cart->cart_contents_total >= 600 ) {
    $woocommerce->cart->add_discount( $coupon_code15 );
    }
    }

    This sort of works. At £200 and £600 the correct codes kick in but the £400 only starts working at £450 for some weird reason.

    Any help on this at the weekend you be awesome. I appreciate you do this in your own time so THANK YOU!

  10. Sorry, me again. I realise that my code isn’t working that well at all. 10% kicks in at £200 but the other two coupons kick in at values a lot higher than I have specified.

    J

  11. Hi there I’m using the following code to apply a 20% discount if the order is greater than £10 how ever i cat seem to get it too work could you send me any information for where I may be going wrong.

    add_action( ‘woocommerce_before_cart’, ‘apply_matched_coupons’ );

    add_action( ‘woocommerce_before_checkout_form’, ‘apply_matched_coupons’ );

    function apply_matched_coupons() {
    global $woocommerce;

    $coupon_code = ’20site’; // your coupon code here

    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

    if ( $woocommerce->cart->cart_contents_total >=10 ) {
    $woocommerce->cart->add_discount( $coupon_code );
    $woocommerce->show_messages();
    }

    }

  12. Hey there!

    Is there a way to instead of having the auto apply of a specific coupon, eg:

    $coupon_code = ’15% off’;

    Is there a way to get the list of all active coupons.

    Basically all our products have specific coupons that apply to them. I want to automatically apply any discount that is available, without manually putting it in the functions.php every time.

    Is that even possible?

  13. Hi Pinaki,

    Appreciate your detail code for the automatic application of the coupon.

    Wondering if you can help me resolve my problem here. I am looking for a way to apply a coupon code to a Single (lease expensive) product item in a Cart. e.g. customer add 2 SG bats at price of rs 100 and rs 200 respectively.

    I want to apply 30% coupon code to my first bat (rs 100 X .70 = 70 price) for the first bat since its a cheapest item in the cart. So customer will pay 270 rs for total purchase.

    I have tried to add this coupon on the Woo commerce by product but it applies to all the products (300 X .70 = 210 price).

    Appreciate if you can help me resolve this issue.

  14. Hi Pinaki, how to automate a discount for an user identified as “paying customer”? I found the piece of code to identify the paying customer, but I don`t know how to use it with your discount automation code. Any ideas…? Many tks for any help!

    /**
    * Is the user a paying customer?
    *
    * @access public
    * @return bool
    */
    function is_paying_customer( $user_id ) {

    $paying_customer = get_user_meta( $user_id, ‘paying_customer’, true );
    if( $paying_customer != ” && absint( $paying_customer ) > 0) {
    return true;
    }

    return false;
    }

  15. Hi … thanks for all the help above. I’m trying to apply 2 coupons automatically at checkout, but there seems to be something wrong with my code. It works about 95% of the time, but for some reason it glitches when customers keep adding/removing items from the cart.

    The 2 coupons I have are — Free Shipping when customers order above $300 (category restrictions apply) and 5% cart discount when customers order above $1000 (category restrictions apply). Here is my code —

    add_action( ‘woocommerce_before_cart’, ‘apply_matched_coupons’ );
    add_action( ‘woocommerce_before_checkout_form’, ‘apply_matched_coupons’ );

    function apply_matched_coupons() {
    global $woocommerce;

    $coupon_code = ‘5% off selected items (conditions apply)’; // your coupon code here

    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

    if ( $woocommerce->cart->cart_contents_total >= 1000 ) {
    $woocommerce->cart->add_discount( $coupon_code );
    $woocommerce->show_messages();
    }

    $coupon_code = ‘free shipping on selected items (conditions apply)’; // your coupon code here

    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

    if ( $woocommerce->cart->cart_contents_total >= 300 ) {
    $woocommerce->cart->add_discount( $coupon_code );
    $woocommerce->show_messages();
    }

    }

    Any advice you can give would be most helpful. Thanks.

    1. Did you ever sort this out? I think I understand the problem, but I don’t know how to work around it. Basically, if you add enough products to get a coupon, that becomes the new ‘cart_contents_total’ amount. For example, if you have a 10% discount at $500 and a 20% at $1000 and the customer adds 500, their new cart total is $450. Then, don’t change anything and hit “UPDATE CART” and it will start having issues because it’s going from that old amount. I’d love to know how to just go based upon the subtotal, not the total carried over from the previous page!

  16. Is it also possible to automaticly add a product once cart total (before shipping) has reached a certain point and then automaticly applying a coupon onto this?

    So for example if cart total is € 25,- item ‘100’ automaticly gets added along with ‘coupon100’ which can make the product free?

    That would be awesome 🙂

  17. Hello,

    Do you know of a way to programmatically take a coupon off a cart?

    Our offer will be 10% off your order, if you have an item from two product categories in your cart.

    I have an array set up which sets a flag for each list of products. But obviously if they apply the coupon it will be allowed. But i would like to remove the coupon if both of these flags are not set to true?

    Any ideas/help would be gratefully received.

    Many Thanks,
    James

  18. hi Pinaki, great help you provide and i almost do not dear to ask but i want to activate coupon if on checkout the customer check a subscribe checkbox (mailchimp registration). is that something you can help me with (wiling to pay)

    thanks

  19. Hi Pinaki!
    I have a special problem with adding a coupon. I’ve got this scenario:
    1. input coupon code in cart, f.e. 123456789 (the code is different in every case)
    2. is the last digit of code = 9 then activate a coupon code “xyz”
    3. if not: return

    Where is the best place to insert this coupon checking ? Do you have a good example of code?

    bye, Thomas

  20. Hello! – quick question:

    trying to use this:

    $cartitems = $woocommerce->cart->get_cart();
    $itemcount = count( $cartitems );
    if($itemcount>1){
    foreach($cartitems as $cartitem){
    $productid = $cartitem[product_id];
    $specialitemid = ‘199’; //// your special item id here
    if($productid == $specialitemid)
    {

    and it works for one product ID – wondering if you could let us know how to use two or three product ID’s ?
    meaning if one of the three products is in the cart it will trigger the discount

    thanks!- Chris

  21. hi Pinaki Bisi.

    How can I add several discounts based on price? Spend 1000 Rs get 5% off – spend $3,000 get 10% off?

    i tried below given code but it’s not working for me.

    add_action( ‘woocommerce_before_cart’, ‘apply_matched_coupons’ );

    function apply_matched_coupons() {
    global $woocommerce;

    $coupon_code = ‘10′;

    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

    if ( $woocommerce->cart->cart_contents_total >= 3000 ) {
    $woocommerce->cart->add_discount( $coupon_code );
    $woocommerce->show_messages();
    }

    $coupon_code = ‘5′;

    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

    if ( $woocommerce->cart->cart_contents_total >= 1000 && $woocommerce->cart->cart_contents_total cart->add_discount( $coupon_code );
    $woocommerce->show_messages();
    }

    }

    plz get me out of this.

    Any ideas/help would be gratefully received.

    Many Thanks,

    kumar.

  22. Hi Pinaki!
    Thank for sharing this!
    I’m actually trying to automatically apply a coupon only when two or more categories are in the cart. I need to apply a coupon only when at least one product of two or more categories are in the cart.

    I tried the following code but unsuccessfully:
    `
    add_action( ‘woocommerce_before_cart’, ‘check_cat_in_cart’ );

    function check_cat_in_cart() {

    global $woocommerce;

    $coupon_code = ‘piumino&copri20’;

    //if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
    $_product = $values[‘data’];
    $terms = get_the_terms( $_product->id, ‘product_cat’ );

    foreach ($terms as $term) {
    $_categoryid = $term->term_id;
    }

    if ( $_categoryid === 300 && $_categoryid === 262 ){
    $woocommerce->cart->add_discount( $coupon_code );
    $woocommerce->show_messages();
    }

    }
    }
    `

    Can you help me with this?
    I really hope so… 🙂

  23. Hi,

    Is this able auto apply to new user? And restrict use one time only? Currently I face a problem, when I tick the “Usage limit per user: 1”, sometime user able apply the coupon in second order or sometime a new user unable to apply the coupon.

    Cheers!
    Elvin

  24. Hi,

    I want the coupon codes to have two discount rates. 10% and 5%. Example – When Coupon1 code is applied product1 will have 10% discount and product2 will have 5% discount. Please can you let me know how can this be done? Thanks.

    Best,
    Deepak

  25. Hi Pinaki!

    Thanks so much for sharing this! Might you know if a similar coupon code could be used to automatically assign a discount to the first, say, 100 clients? I guess the code would need to 1) automatically associate the first 100 buyers with the coupon code, and 2) automatically implement the discount. I wonder if the automatic association of the first 100 clients might be more complicated and requires a plug-in instead.

    Thank you in advance!
    Madison

  26. Hi Pinaki,

    You seem to be the answer to everyone’s problem. I wonder if you can modify your code to do the following:

    I use WooCommerce Bookings with Person Types which are just variations, however, in the Coupon functionality they are not picked up as variations so I cannot set a discount coupon for a particular Person Type.

    I wonder if your code can be modified to apply only to a specific product and a specific Person Type (variation). If you look at http://seahorseworld.info/shop/seahorse-world-tour/ you will find a special deal for seniors. I want to apply the discount only to this option.

    Is it possible? Are you able/willing to share the code?

    Thank you,
    Louise

  27. Hi i have used woocommerce rest api for mobile application but i got issue for coupon apply to new order it don’t work.I meant when i care new order and apply coupon but i get discount on order have you any code or solution for that..?

  28. Hi. Need your help! There is a code – adding an automatic coupon in the shopping cart.

    cart->has_discount( $coupon_code ) ) return;
    if ( WC()->cart->cart_contents_total >= 1100 ) {
    WC()->cart->add_discount( $coupon_code );
    }
    }
    ?>

    Need to make this function worked only when pickup from store (local_pickup), but unfortunately can’t figure this out, need help !

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s