WooCommerce: “Buy One Get One” (Without a Plugin!)

Case scenario: if you add a product to cart with a specific SKU, you need another product automatically added to cart and a 100% coupon discount applied to it as well.

So here follows the PHP snippet of course!

WooCommerce: add free gift to cart if product is added to cart

PHP Snippet: Add “Product Gift” to Cart if SKU is Added to WooCommerce Cart


/**
 * @snippet       Buy 1, Get Free Product as a Gift - WooCommerce
 * @how-to        Watch tutorial @ https://businessbloomer.com/?p=19055
 * @sourcecode    https://businessbloomer.com/?p=21732
 * @author        Rodolfo Melogli
 * @compatible    Woo 3.5.3
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

add_filter( 'woocommerce_add_to_cart_validation', 'bbloomer_add_gift_if_sku_added_cart', 10, 3 );

function bbloomer_add_gift_if_sku_added_cart( $passed, $product_id, $quantity ) {
global $woocommerce;

/* enter array of SKUs that give gift */
$skuswithgift = array('armpar','armsup');

/* enter SKU of product gift */
$giftsku = 'starter';

/* enter name of coupon that gives 100% discount for specific product gift */
$coupon_code = 'xxxyyyzzz'; 

$product = wc_get_product( $product_id );

if ( $product->get_sku() && in_array( $product->get_sku(), $skuswithgift ) ) {
	WC()->cart->add_to_cart( wc_get_product_id_by_sku($giftsku) );
	wc_add_notice( __( 'Hey, Supporter! As promised, I added #CustomizeWoo Video Lessons for Free - you will be able to access them in a single place (~ My Courses ~) and get premium support.', 'woocommerce' ), 'success' );
	$woocommerce->cart->add_discount( $coupon_code );
}
return $passed;
}

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!

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

36 thoughts on “WooCommerce: “Buy One Get One” (Without a Plugin!)

  1. Hello,

    The code above works very well for one product, but here is a tested scenario that opens an unwanted door and some other issue (described in Scenario 2):

    Scenario 1: let’s say the visitor adds to cart product A, which is the main one, and gets his cart automatically filled with product A + product B (which is the “gift” product). Now, the user clicks several times on the “+” button for product B (the “gift”). What happens is that the discount is applied automatically to all the B products (“gifts”), such that in the end, the buyer gets 1 main product (A) and indefinitely many “gifts”.

    Scenario 2: Another issue with this code is that if the client buys 3 products A (the main ones), he only gets one product B (the “gift”). He has to adjust manually the quantity of “gifts”, but then we return to Scenario 1, where he can empty the stock of “gifts”.

    1. Hi Vladimir, thanks for your feedback. You could force the gift to be purchased “only once per order” to fix Scenario 1 (from its settings). This will of course go against Scenario 2, but you have to make a choice. Coding a “sync” between product A and product B 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. Hello, Rodolpho, and thanks a lot for your reply.

        Eventually, I have managed to code it, thanks to your magnificent tutorials here.
        My problem was the following: I have to build a conference website where there is a connected event (a workshop after the conference). Whoever buys a ticket for the workshop, he gets one ticket free for the conference. The same goes for multiple purchases — N workshop tickets will get the buyer N free conference tickets.
        I had also to implement reductions for multiple purchases (3 — 5%, 4-10 — 10%, >11 — 15%) for both workshop and conference tickets, and also make sure that if a buyer gets N workshops and N + m conferences, he will have to pay for the additional m conference tickets in his cart (according to the reduction rules imposed by my customer).
        Thanks to your wonderful tutorials, I have managed to get the job done (and also managed to start understanding how the Woocommerce plugin is coded).
        Mille grazie for the inspiration found on your website here!

        Vladimir.

        1. Excellent!

  2. Can’t seem to find this tutorial which is inside the snippet: https://businessbloomer.com/?p=19055
    Where can I find the tutorial now?

    1. Sorry about that Paul – should work now. Let me know

  3. Thank you so much!
    I appreciate you helping us out with this useful tip.
    I modified a bit so where you have:

    $giftsku = ('Product X');

    I changed it to

    $giftsku = array('Product X','Product Y','Product Z'); 

    The problem I’m having is that the discount is still applied when the product that gives the gift is removed from the cart. What modification would I need to use in order to fix that? Thanks!

    1. Hey Chris, thanks so much for your comment! Yes, this is possible – 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. Hi,

    This doesn’t seem to be working on your own sample site at present, so won’t even try to implement!

    Let us know when it’s fixed…

    Cheers

    1. Ahah good point Matt! I’m just not using it anymore, however the snippet still works ๐Ÿ™‚

  5. Hello & thanks for a great piece of code!
    See I have kind of trouble after implementing this code in my site I’ve got a woocommerce error message “Sorry this product cannot be purchased!” and it diesn’t appear in a Cart.

    I tried to use Grouped product or Single product (to be added in cart), with or without prices but no luck!

    1. Hey Dime ๐Ÿ™‚ Did you make sure to change all the SKUs and coupon codes inside the snippet?

  6. How do i apply the gift to ALL products in my website not only those SKU in $skuswithgift ?

    1. Avi, 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. Hello ,

    I applied above code in my functions.php file. And i am able to manage to add another product in the cart. But my coupon is not working. My another product get added in the cart, but it’s price does not get discount to Zero, please help me out of this/

    1. Hey Divya, 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

  8. Hi

    I have added the code. So I also need to add a coupon that has 100% discount applied to the Free Gift right?

    Many Thanks

    1. Correct Dave! Or give the Gift a zero price ๐Ÿ™‚

  9. Hi Rodolfo,
    thanks for your snippet.

    Is there a way to flush the gift if the products that activate it will be removed from cart?

    Thanks in advance for your reply.

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

  10. Hi Rodolfo,
    Thank you for this great snippet. Its working only for simple product. How do i make it work for variable product.
    when someone buy particular variation, i tried to add variation sku, but its not adding free product to cart, Thanks in advance

    1. Hello Sunny, 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 , i just want a code for my website,
    if a person buy 3 item same 1 item free
    if its 6 then 2 free
    if its 10, 3 free

    can you help me on that

    thanks

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

  12. Hi,

    Is it possible to have this kind of concept… buy 1 product then after successfully shared to facebook, customer can able to choose another 1 product for free..

    Thanks

    1. Hey Marvin, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here on the blog. Thanks a lot for your understanding! ~R

    2. hi,

      thanks for the reply, i just played some codes to get what i want.. but i have one problem.

      Just want to ask if there’s anyway to change the add_to_cart button text for a certain product category..

      I already change the global product add to cart text into +show OFFER,. here’s the code

      function add_cart_button_replace() {
      global $product;
       $link = $product->get_permalink();
       echo do_shortcode('<a href="'.$link.'" rel="nofollow">+show OFFER</a>');
      }
      

      but what i want is to change the certain product category like “free-products”. when i open the archive of that certain category, it should be +choose me(with cart link) not the +show OFFER..

      Is that possible? thank you so much for the help..

      1. Marvin, yes, it is possible – but as I said I cannot help with custom work here in the blog comments. Thank you ๐Ÿ™‚

  13. How do I change this code to add to cart automatically if the price is more than $ 50 for example?

    1. How do I change this code to add to cart a gift automatically if the price is more than $ 50 for example?

  14. Can this be changed to add product x for any product added to cart?

  15. Hi,
    It’s great but if the first product (the one that gives the gift) is removed from the cart, the gift is still there and free that might be a problem.

    1. Julia, thanks for your comment, and spot on! Maybe this could help: https://gist.github.com/yojance/042350679b5222fcf16e

    2. Hi, I am having this same issue, did you ever get it fixed?

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 *

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