WooCommerce: Order a “Free Sample” @ Single Product Page

Recently I was on a coaching call with a client and the “Free Sample” challenge came up. Client has 400+ products on the website and had no intention of adding a free variation to each product manually.

So, I promised to myself I was going to study a different approach. And today you get it for free – nice! Needless to say, a comment and a social media share are much appreciated πŸ™‚

Display an “Add Free Sample to Cart” button @ WooCommerce single product page

Requirements for “Free Sample” – WooCommerce

Before digging into PHP, you will need to create a brand new simple hidden product (otherwise the code won’t work. Or call it whatever you like, but make sure to change the PHP snippet below accordingly).

Here are the requirements:

  • Title: whatever you like e.g. “Free Sample
  • Price: “0
  • Catalog Visibility: “Hidden
  • Inventory: “Sold Individually

Make sure to remember the product ID of this new product, because you will need to use it in the PHP snippet πŸ™‚

PHP Snippet: “Free Sample” Add to Cart Button @ WooCommerce Single Product Page

/**
 * @snippet       Add Free Sample to Cart @ Single Product
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 5
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

// -------------------------
// 1. Display Free Sample Add to Cart 
// Note: change "123" with Free Sample ID
 
add_action( 'woocommerce_single_product_summary', 'bbloomer_add_free_sample_add_cart', 35 );
 
function bbloomer_add_free_sample_add_cart() {
	?>
		<form class="cart" method="post" enctype='multipart/form-data'>
		<button type="submit" name="add-to-cart" value="123" class="single_add_to_cart_button button alt">Order a Free Sample</button>
		<input type="hidden" name="free_sample" value="<?php the_ID(); ?>">
		</form>
	<?php
}
 
// -------------------------
// 2. Add the custom field to $cart_item
 
add_filter( 'woocommerce_add_cart_item_data', 'bbloomer_store_free_sample_id', 9999, 2 );
 
function bbloomer_store_free_sample_id( $cart_item, $product_id ) {
	if ( isset( $_POST['free_sample'] ) ) {
			$cart_item['free_sample'] = $_POST['free_sample'];
	}
	return $cart_item; 
}
 
// -------------------------
// 3. Concatenate "Free Sample" with product name (CART & CHECKOUT)
// Note: change "123" with Free Sample ID
 
add_filter( 'woocommerce_cart_item_name', 'bbloomer_alter_cart_item_name', 9999, 3 );
 
function bbloomer_alter_cart_item_name( $product_name, $cart_item, $cart_item_key ) {
	if ( 123 === $cart_item['product_id'] ) {
		$product = wc_get_product( $cart_item["free_sample"] );
		$product_name .=  " (" . $product->get_name() . ")";
	}
	return $product_name;
}
 
// -------------------------
// 4. Add "Free Sample" product name to order meta
// Note: this will show on thank you page, emails and orders
 
add_action( 'woocommerce_add_order_item_meta', 'bbloomer_save_posted_field_into_order', 9999, 2 );
 
function bbloomer_save_posted_field_into_order( $itemID, $values ) {
    if ( ! empty( $values['free_sample'] ) ) {
		$product = wc_get_product( $values['free_sample'] );
		$product_name = $product->get_name();
		wc_add_order_item_meta( $itemID, 'Free sample for', $product_name );
    }
}

Where to add this snippet?

You can place PHP snippets at the bottom of your child theme functions.php file (delete "?>" if you have it there). 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.3.

If you think this code saved you time & money, feel free to join 14,000+ WooCommerce Weekly subscribers for blog post updates or 250+ Business Bloomer supporters for 365 days of WooCommerce benefits. Thank you in advance :)

Need Help with WooCommerce?

Check out these free video tutorials. You can learn how to customize WooCommerce without unnecessary plugins, how to properly configure the WooCommerce plugin settings and even how to master WooCommerce troubleshooting in case of a bug!

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.

112 thoughts on “WooCommerce: Order a “Free Sample” @ Single Product Page

  1. HI Rodolfo, this will work in Elementor?

    1. Haven’t tested it, but I don’t see why not

  2. This is perfect for a new site I’m building for a client. Code is added to functions.php and the button displays but when clicked nothing happens.

    Step 2 doesn’t seem to be firing.

    It’s a custom theme if that makes any difference. Client is happy to pay for a fix.

    1. Thank you. Did you change anything in part 1? Please share your code and I’ll see if I can identify the error

  3. Hey

    I added this but when I click the button, nothing happens? I used the name you used etc and just copied the code? you mention changing the id but I’ve no idea where to change it! Can you help?

    Thanks!

    1. Hey Ryan. You need to change this:

      value="123"
  4. Hello Rodolfo,

    The piece of code was working fine, but now I want to build a custom template for a single product with Elementor. The Sample button doesn’t appear in this template. How can I fix that?

    Best regards,
    Michel

    1. Hi Michel, 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!

  5. Hi!
    Thanks for the code, it works great!
    The only problem for me is that de product in the cart only shows ‘Free sample for (product name)’ and not for the exact variation.
    Which makes it hard to know which color the (wallpaper) sample has to be.
    For example with variable products that are available in green, red and yellow.
    Is there a possibility to let it copy the SKU as well?

    1. Hi Eline, 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. Hi Rodolfo,
    I’m getting just the name ‘Sample’ in my cart, not the product name also, This did work until I installed ‘woocommerce Add ons ultimate’
    Which is an essential plugin for me. If I disable the plugin all is good again. Is there a fix.

    Thanks in advance.

    1. Hi Nigel, 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!

  7. Hi,
    All good until I get to the basket. I can only get Free delivery for free sample and a purchased product or delivery charge for free sample and a purchased product. Not separate. Tried all options in woo shipping options. Perhaps they can not be mixed? ID correct.
    Great your helping out! Any advise appreciated.

      1. Cool! What was it?

        1. I installed the free version plugin called ‘Flexible Shipping’. Did the trick.

          1. Hi Nigel,

            how did you setup “Flexible Shipping” to do the trick? πŸ˜€

            Struggling with the same problem

            Best Regards

  8. Any reason why my basket just shows just word sample and isn’t grabbing the product name
    I am assuming this works for variations or perhaps not?
    Even with simple products I am getting product name “Sample – Sample” in basket

    I modified the code as the samples aren’t free I saw your note
    “but make sure to change the PHP snippet below accordingly).”

    And changed anywhere that free_sample was mentioned to just “sample”

    1. Did you also change this line: $product_name == “Free Sample”?

  9. Hi great tutorial, works perfectly!

    Quick question (hopefully), how do I set the free sample quantity to X? I’ve obviously not checked the “Sold individually” box and tried adding the following function after “bbloomer_store_free_sample_id’.

    However this doesn’t work!? If you could help that would be really appreciated!

    Thanks

    1. Hi Luke, 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. Every item ordered with a free sample option is coming through named ‘Free Sample for (xxx)’ even if the full item is ordered. How can I fix this?

    1. Screenshot please?

  11. Hi. How would i ammend it so the free sample button only appears on specific product categories? I have products and services that a free sample cannot be provided for

    1. Hi John I suggest you take a look at “conditional logic”: https://businessbloomer.com/woocommerce-conditional-logic-ultimate-php-guide/. Enjoy πŸ™‚

  12. Great stuff m8!

    Good code and after some tweaking it did the trick.

    Like others already said, im trying to add the product_thumbnail to the whole code. Having trouble arranging that.
    If anyone has a solution, would love to read it!

    greetings Karel

    1. Thanks!

      1. Hi Rodolfo,

        Since this month the sample button doesn’t work correctly on our page anymore.
        Before it didn’t require a height or other values in a form in the product page, the sample button could be clicked whenever you wanted. Now it depends on the required fields in the page.

        Any idea how could this could have happened?

        1. No idea. Disable all plugins and switch theme and see if it works

          1. Thx for your quick reply.

  13. Hi,
    Thanks for the code snippet, very useful πŸ™‚ Just a headsup, I’m getting this deprecated warning from the fourth section of the code

    [20-Jul-2020 11:17:30 UTC] woocommerce_add_order_item_meta is deprecated since version 3.0.0! Use woocommerce_new_order_item instead.

    1. Cheers!

  14. Can a price be set for the shipping of Free Samples?
    We sell large items, which the standard shipping charge has to be quite high. So charging the same shipping price for a small sample of a product would be quite ridiculous.

  15. I have the need for an actual ‘Samples Basket’ we supply greetings cards and offer up to 6 samples free of charge, so the customer can build a samples basket and then click to order. Does this or anything else you may have done come close?

    1. Hi Andrew, 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!

  16. Perfect !!
    But I need to add a free sample for all product prices I $4.99, how to add this?

    1. Simply add the regular price to the free sample?

  17. This is confusing in the backend. All product names are coming in as Free Sample. Is there a way to concatenate the Product Name to the word “Free Sample” inside the order?

  18. Hello!
    Amazing snippet wonder if you can help, I have different products some samples cost Β£3 and some are free how would I make this work with separate pricing

    1. Hi Luke, 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!

  19. what should I do if I want to add different prices for each sample. please give me hits or write code here. I am freelancer. thanks

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

  20. Amazing snippet thank you! Just curious if you could help? I want to use these snippet for only for certain product categories, ie all products in category A & C have the sample button but the products in category B do not. Any help with that would be amazing

    Thank you once again

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

  21. hi there! Great snippet
    IΒ΄ve just tried and does not concatenate text “Sample” with product name in cart and checkout.
    Only display the title of sample product (β€œFree Sample” by default).
    IΒ΄m using last version of woocommerce and wordpress. Could it be the problem? thanks!

    1. Hi Pau, thanks for your comment! I just tested this again with Storefront theme and it works perfectly. Maybe your theme (or another plugin) is messing/conflicting with my snippet?

      To troubleshoot, disable all plugins but WooCommerce and also switch temporarily to “Twentyseventeen” theme (load the snippet there in functions.php) – does it work? If yes, you have a problem with your current theme or one of the plugins.

      Hope this helps!

      R

      1. The problem is that it isn’t visible in the backend when looking at the order. The product name only says Free Sample and the Product name is separate as custom meta. Could you confirm if the name in the backend when looking at the order should say “Free Sample” or “Free Sample(Product name)”?

        1. Hey Paul, I’ve just revised the snippet, however it was already showing the name of the Product as “order item meta”. If you correctly entered the product ID and named the free product “Free Sample”, it will work

  22. Hi Rodolfo, this is a brilliant fix, thank you! I have one query. I have used Elementor to create a new template for single products, and I would like to do one of two things:
    a) Have the button appear when using this different template OR
    b) Have a custom-added button call the function for adding a free sample.

    Any advice on how to tackle this? I appreciate it may need a non-complementary solution!

    1. Yes Gareth, 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!

  23. Thanks for this great feature,

    One question, How do i add the SKU to the details? so that we can now what to supply?

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

  24. This breaks my cart page:

    // ————————-
    // 3. Concatenate “Free Sample” with product name (CART & CHECKOUT)
    // Note: rename “Free Sample” to your free sample product name

    add_filter( ‘woocommerce_cart_item_name’, ‘bbloomer_alter_cart_item_name’, 10, 3 );

    function bbloomer_alter_cart_item_name( $product_name, $cart_item, $cart_item_key ) {
    if ( $product_name == ‘Free Sample’ ) {
    $product = wc_get_product( $cart_item[‘free_sample’] );

    }
    return $product_name;
    }

    Deleting that code allows my cart page to load properly.

    Any idea how to fix this?

    1. Hi Paul I think you’re missing a line from my snippet – let me know

  25. i have to show this button on specific products, how can i do that??

  26. This is great. If I want to be able to disable it for certain categories how can I do this please.

  27. Hello, thank you for sharing this solution. Is there a possibility of assigning a fixed price to any sample order? Thanks!

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

  28. Hi Rodolfo,
    thank you very much for the snippet. It almost does as it is supposed to do. Unfortunately it doesn’t change the name of the Free Sample Product to the name of the actual product I put in my cart. Do you think it’s a mistake by my side or maybe the snippet needs to be updated as we are a couple of wordpress updates ahead?
    Thank you so much for the work you put into this!
    Kind regards,
    Christine

    1. Hello Christine, it works for me! You need to make sure your product is actually called “Free Sample” and that its ID is entered here:

      value="953"

      …otherwise it won’t work. Let me know

    2. Hi Rodolfo,
      okay, it works with that word. Unfortunately my customers speak German, so that is why I tried to translate Free Sample to Stoffmuster and just use the logic of the snippet. But there seems to be a restriction and the snippet just works with the English words.
      I would be happy to get a quote from you on custom work to customize the translation. See my request for a quote from Friday.
      Kind regards,
      Christine

      1. I answered to your email, thanks a lot!

  29. how can I pass the thumbnail image to the order? Do I need to utilise woocommerce_order_item_thumbnail ??

    thanks in advance

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

  30. Hi Rodolfo. Thank you for making this functionality and making it available. I need to restrict it to a certain category, as not all products are suitable for free samples. However I cannot get it to work with the conditional logic that you refer us to try out. The functionality works perfectly without the conditional logic, but not with it (the button doesn’t show). If I just echo some text with the conditional logic script, that works fine. I hope you can help me in the right direction.

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

  31. Dear Rodolfo.
    It is wonderful and still works with latest WooCommerce & WordPress.
    So easy to modify and just perfect! Thanks!

    1. Excellent πŸ™‚

  32. Wow! Great. It’s what I was looking for. Is there any way to show Free Sample button for specific categories only? I have a store. I like to offer free samples for perfumes not for make-up.

    1. Hello Kibria – thanks so much for your comment! I suggest you take a look at “conditional logic”: https://businessbloomer.com/conditional-logic-woocommerce-tutorial/ and https://businessbloomer.com/woocommerce-conditional-logic-ultimate-php-guide/. Let me know πŸ™‚

  33. Hi Rodolfo,

    What a great snippet of code! Just what I was looking for.

    in Step 4. (to my very limited PHP understanding) it looks like $product_name should add the product name to “Free Sample”.
    ie: Free Sample (Product Name).

    Is this correct? if so, it doesn’t seem to work for me. It still just says “Free Sample”.

    Looking forward to your response πŸ™‚

    1. Thank you Werner! No, at step 4 I concatenate (Free Sample) to the existing Product Name in the Cart and Checkout. It works in my development site πŸ™‚

    2. Hmm, it doesn’t seem to work for mine running the latest version of WC and WP. Aparently woocommerce_add_order_item_meta is depreciated in the latest version of woocommerce? Could this be why?

      1. Possible πŸ™‚ But probably you’re using an old version of this snippet, I already use “wc_add_order_item_meta” in here. Try revising your snippet and let me know

  34. hey hey this is wicked. and just what I needed so thanks very much

    Thanks for this. is there a way to log the time difference between the customer ordering the sample then coming back to order the full product?

    Thanks again

    Nick

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

  35. p-Content/Plugins/Code-Snippets/Php/Snippet-Ops.Php(352) : Eval()’D Code On Line 58

    i get a php error in the cart when i used this

    1. Hey David! What’s on line 58?

    2. just a curly brace. strange thing is ive used this exact snippet before without issue tested on another install and it worked fine maybe a theme issue?

  36. Hello again, does anyone know how “not” to show this ‘Order Sample’ for certain products that don’t have samples available? In other words, is there a quick easy way to turn this sample feature off for specific products? Thanks in advance.

    1. Hey Rod, thank you so much for your comment! I suggest you take a look at “conditional logic”: https://businessbloomer.com/conditional-logic-woocommerce-tutorial/ and https://businessbloomer.com/woocommerce-conditional-logic-ultimate-php-guide/. Let me know πŸ™‚

  37. Dam good! this was a super usefull snippet:) ! Question. Is there a way of also putting the product name you are ordering in the cart?

    Free sample : Product name

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

  38. Hi can this be changed to be able to select the categories it needs to apply to?
    Also I would need it implementing to the woomobify plugin too if this possible?
    Thanks and look forward to your reply

    1. Hi Colin, thanks for your comment! Yes, I suggest you take a look at “conditional logic”: https://businessbloomer.com/conditional-logic-woocommerce-tutorial/ and https://businessbloomer.com/woocommerce-conditional-logic-ultimate-php-guide/. Let me know πŸ™‚

  39. Hi there! This worked great!… I was able to also add the button to the main products display page (i.e. shop page). Thank you.

    1. Brilliant, thanks Rod πŸ™‚

  40. Do you offer the customization services necessary for this code’s additional functionalities mentioned by others here? I also need the ability to “Order Free Samples” with some additional function/conditions. Please let me know, thank you.

    1. Hello Rod, thanks for your comment (and great name by the way :)). Yes, I’m available every day for paid work – if you’d like to get a quote, feel free to contact me here. Thanks in advance! ~R

  41. Great piece of code, but I can’t seem to add a shipping option to the free sample – any idea how I would do this please? My product sample is free, but the customer will need to pay postage, so I need to allocate a shipping class to it. I’ve added this normally in Product Data – Simple Product > Shipping but it doesn’t seem to pick it up correctly. All help gratefully received!

    1. Ian, thanks so much for your comment! Unfortunately this is custom troubleshooting work and I cannot help here via the blog comments. Thanks a lot for your understanding! ~R

  42. This is amazing, the 2 plugins I found were so hit and miss. There is one thing extra I need it to do, is there any way to make it copy the SKU as well as the product names. I am using it on a carpet store and different carpets are annoyingly called the same thing.

    1. Andy, thanks so much for your comment! Yes, this is definitely 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

  43. Can the button be unique to categories as appose to all products? this would be greatly helpful for me.

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

    2. Hi Chris. Did you ever find a solution for this – I have the same issue as you?

    3. In case anybody is still looking for a way to make the button appear only for certain categories, the solution provided here worked for me: https://stackoverflow.com/questions/45118802/display-a-custom-button-on-woocommerce-product-pages-only-for-certain-categories

      Basically modified Rodolfo first bit of code to this:

      // -------------------------
      // 1. Display Free Sample Add to Cart 
      // Note: change "12345" with Free Sample ID
       
      add_action( 'woocommerce_single_product_summary', 'bbloomer_add_free_sample_add_cart', 35 );
       
      function bbloomer_add_free_sample_add_cart() {
      global $product;
      $product_cats = array('category1','category2','category3');
      if( has_term( $product_cats, 'product_cat', $product-&gt;get_id() ) ){
      ?&gt;
      
      Order a Free Sample
      &lt;input type=&quot;hidden&quot; name=&quot;free_sample&quot; value=&quot;"&gt;
       
      &lt;?php
      }
      }
      
      

      Hope this helps πŸ™‚

  44. Hi Rodolfo,
    Can Woo ensure only one free sample offer is made available to just one unique customer, to ensure unlimited free samples are not being ordered by the same person per order or per day or week etc?

    1. Denis, thanks for your comment! Yes, an additional snippet can be added to limit the Cart to only 1 free sample, similar to this (additional code is required): https://businessbloomer.com/woocommerce-allow-1-product-cart/

  45. You are a genius. Thank you so much for this.

    1. Thanks for your feedback Olga πŸ™‚

  46. Excellent, this helped a lot. Business Bloomer Forever!

  47. Now we’re talking! this is a hella dope snippet.

    More from that please!

    1. Great to hear that Ahmed πŸ™‚

  48. You are awesome!

    1. Ahhhh, thank you Faizan πŸ™‚

Questions? Feedback? Support? Leave your Comment Now!
_____

If you are writing code, please wrap it between shortcodes: [php]code_here[/php]. Failure to complying with this (as well as going off topic, not writing in English, etc.) will result in comment deletion. 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 BloomerArmada to get blog comment reply priority, ask me 1-to-1 WooCommerce questions and enjoy many more perks. Thank you :)

Your email address will not be published.