WooCommerce: Add Product to Cart On Visit Programmatically

Quite an interesting functionality! A WooCommerce client wanted their Cart pre-filled with one product as soon as their customers accessed the website. I don’t remember the exact reason, but this could be useful when you want to give them a free product by default, or you want to send your visitors straight to checkout with a product already in the cart without letting them add anything first.

Adding an item to cart programmatically is the same as “automatically”. Basically, all users will have a default, non-empty Cart filled with an item of your choice. So, let’s see how this snippet works!

WooCommerce: Add Product to Cart Programmatically
WooCommerce: Add Product to Cart Programmatically

PHP Snippet: Add Product to WooCommerce Cart Automatically On Visit

/**
 * @snippet       Add Product to WooCommerce Cart Programmatically
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.9
 * @community     https://businessbloomer.com/club/
 */
  
add_action( 'template_redirect', 'bbloomer_add_product_to_cart_automatically' );
  
function bbloomer_add_product_to_cart_automatically() {
          
   // select product ID
   $product_id = 21874;
          
   // if cart empty, add it to cart
   if ( WC()->cart->get_cart_contents_count() == 0 ) {
      WC()->cart->add_to_cart( $product_id );
   }
    
}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce: Custom Add to Cart URLs – The Ultimate Guide
    In WooCommerce you can add a product to the cart via a custom link. You just need to use the “add-to-cart” URL parameter followed by the product ID. This tutorial will show you how to create custom URLs to add simple, variable and grouped products to the cart – as well as defining the add […]
  • WooCommerce: Hide Price & Add to Cart for Logged Out Users
    You may want to force users to login in order to see prices and add products to cart. That means you must hide add to cart buttons and prices on the Shop and Single Product pages when a user is logged out. All you need is pasting the following code in your functions.php (please note: […]
  • WooCommerce: How to Fix the “Cart is Empty” Issue
    For some reason, sometimes you add products to cart but the cart page stays empty (even if you can clearly see the cart widget has products in it for example). But don’t worry – it may just be a simple cache issue (and if you don’t know what cache is that’s no problem either) or […]
  • WooCommerce: “You Only Need $$$ to Get Free Shipping!” @ Cart
    This is a very cool snippet that many of you should use to increase your average order value. Ecommerce customers who are near the “free shipping” threshold will try to add more products to the cart in order to qualify for free shipping. It’s pure psychology. Here’s how we show a simple message on the […]
  • WooCommerce: Cart and Checkout on the Same Page
    This is your ultimate guide – complete with shortcodes, snippets and workarounds – to completely skip the Cart page and have both cart table and checkout form on the same (Checkout) page. But first… why’d you want to do this? Well, if you sell high ticket products (i.e. on average, you sell no more than […]

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. Follow @rmelogli

46 thoughts on “WooCommerce: Add Product to Cart On Visit Programmatically

  1. When using the Variable product doesn’t work.

    1. Hi Abdelrahman, did you try use the variation ID?

  2. For some reason this function breaks the Rest API of my site. Added the following on top to prevent that from happening.

    [php]
    if(!WC()->cart ){
    return;
    }
    [php]

  3. Super helpful – thank you!

  4. Hello, I have read all your posts and I really appreciate your work, it has helped me enormously.
    I wanted to ask you a question to see if you could help me, I have already managed to add products programmatically but now I need to add a product to the cart but that it is hidden from the buyer but that it appears in the order. This to be able to identify the vendor of the product through a hidden product without complications other than adding a product for each vendor you have. Without installing another plugin or more complications with commissions.

    I would appreciate your help and I look forward to your response

    1. Hello Jesus! Did you try setting up the product as “hidden”?

  5. Hi Rodolfo, I’ve been working off a few of your guides (which are great) but I’m stuck on one issue. I’m using WooCommerce strictly as a catalog site directing users to reach out for actual purchases, but have integrated the shipping calculator on the individual product pages in order to provide shipping estimates with ajax. The problem is that when the request goes through, WooCommerce registers that the cart is empty, and the shipping classes I’ve set up don’t engage so the price only comes out as the flat rate. So essentially what I want to do is automatically add 1 of the product to the cart each time an individual product page loads (broken out by category). And then have the script empty the cart and add 1 on any subsequent visit to a different individual product page. I tried based on the global $products id but am having no luck. Any notes would help. Thanks!

    1. Ciao Angelo, 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. Man! I am so happy with this code. I have used it for a couple of weeks and also the customers are happy with my ‘suggestion’.
    Saying that, I will add some free products to my shop and when these (category) are in the cart, then this extra product must NOT be added.
    So if found some code what to do when the cart has a certain cat, but then I get lost with this action.
    Can you help me out on that?

    1. Thanks so much for your comment! If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  7. thanks for the code. but there is a way to prevent customers to delete this product ??

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

  8. Thanks so much, Mr. Rodolfo for giving us this. I used this today the 15th of April for a client’s work and it works perfectly

    1. Cool!

  9. When using

    WC()->cart->add_to_cart();

    , how can I refresh the cart so the changes are reflected?

    1. Uhm, maybe you need to “AJAXify” the snippet. 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. Hi, Can you Add Product to Cart Programmatically depending on user role?
    Thanks, Cam

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

  11. Hello

    I want to have a product link that one product add to cart automatically and the user goes to the checkout page directly.
    Please help me, how can I do this?
    thanks

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

  12. Salve,

    vorrei che la quantitร  del prodotto inserito partisse da zero e non da uno รจ possibile?
    oppure
    Aggiungere questo prodotto sono nel caso in cui il cliente scelga una determinata variazione degli attributi dei prodotti presenti nello shop

    1. Ciao Denise, you can’t add an item to cart with quantity = 0 ๐Ÿ™‚

  13. Hi Rodolpho,
    Great work as usual.
    I want to use your code but to show a different product depending on the amount of items.
    I was thinking of using array but I can’t seems to get it right.
    I would really appreciate if you or anybody could give me the right code.
    That’s what I have so far:

    add_action( 'template_redirect', 'add_product_to_cart' );
    function add_product_to_cart() {
    $product_id = array ( 'product1', 'product2', 'product3', 'product4' );
    	
    if ( WC()->cart->get_cart_contents_count() <= 2 ) {
    WC()->cart->add_to_cart( $product_id, 1 ); }
    
    else if ( WC()->cart->get_cart_contents_count() <= 6 ) {
    WC()->cart->add_to_cart( $product_id, 2 ); }
    
    else if ( WC()->cart->get_cart_contents_count() <= 12 ) {
    WC()->cart->add_to_cart( $product_id, 3 ); }
    
    else if ( WC()->cart->get_cart_contents_count() <= 24 ) {
    WC()->cart->add_to_cart( $product_id, 4 ); }
    }
    
    1. No I wouldn’t use an array. Just put the product ID inside the add_to_cart(XYZ) function

  14. Hi, lately Iโ€™m working on. Few products and Iโ€™m googling quite a lot with a lot of questions here and there and your site pops up most of the time with really clever approaches to the solutions. So for that part, thanks a lot.

    I was wondering if it is possible so I can add more than one of the same product Iโ€™d (so qty increase) and out of curiosity and maybe others, add more than one different Id

    Thanks kind regards

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

  15. Hello,

    What do you replace “bbloomer_add_product_to_cart” with? Am I suppose to change the “bbloomer” part?

    1. Hey there, thanks for your comment! Nothing if you like. That’s just the name of the function I came up with. You can use “my_custom_function_name” if you prefer ๐Ÿ™‚

  16. Hi Rodolfo, i was trying to do something similar to this but it has to be done client side, is there a an add to cart function that uses javascript instead of php?

    I’m trying to add a variable product where the variable is decided after some input from the user (not them deciding which one like the base dropdown does).

    I’ve been struggling with ways to do this for a few weeks and any help you could provide would be most appreciated.

  17. Hi Rodolfo
    this is very helpfull
    i hope i can read more resources from you again in the future
    keep it up!

    1. Thank you ๐Ÿ™‚

  18. I have found many code for this on internet but all are producing an error. At last I have found this and this snippet is working fine without any error.
    Thanks Rodolfo.

    1. Excellent ๐Ÿ™‚

  19. Is there a way to add a custom meta for each individual cart item?
    “custom_reference” and “price” comes from an add-on textbox.
    I was able to modify the price for each individual cart items, but I can’t seem to make the custom_reference work.

    cart item 1: https://yourdomain.com/?add-to-cart=25&price=100&custom_reference=REF001
    cart item 2: https://yourdomain.com/?add-to-cart=25&price=990&custom_reference=REF002
    cart item 3: https://yourdomain.com/?add-to-cart=25&price=500&custom_reference=REF003

    custom_reference & price comes from a variable that is being passed to the query string
    https://yourdomain.com/?add-to-cart=25&price=var_1&custom_reference=var_2

    I think this will help the others as well ๐Ÿ™‚
    This is something very useful especially for products with extended variable pricing and referencing.

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

  20. hi is it possible to modify the price of this product_id?

    The API is
    add_to_cart( $product_id, $quantity, $variation_id, $variation, $cart_item_data );

    Any tips on which params should i modify to change the price?

    Thanks!

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

  21. Hi Rodolfo,
    This is really helpful, thank you! I’ve had issues with a payment plugin, when the order is created by the admin and then customer goes to pay via payment link or from the account, the payment is denied (if) because the cart is empty.
    As I’ve searched for solution, I happened to google a lot of similar problems unsolved.
    But I’ve noticed that if there is anything in the cart, the payment goes through successfully (and it does not matter what, because the order totals does not depend on the cart in this case). So adding a single product in the beginning of the payment plugin function

     function process_payment($order_id){

    worked just fine.

    Yet, it is not a universal solution (since you need to add certain product id), can you suggest anything better to bypass that “requirement” for a cart not to be empty if it is a payment-link order?

    1. Hey Slon, thanks for your comment! The cart shouldn’t be empty, try some troubleshooting: https://businessbloomer.com/woocommerce-solving-cart-empty-issue/

  22. Hi Rodolfo!
    Is it possible to programmatically modify the price of a product only for a particular customer if it enters a promotional code and add it to the cart?
    Thank you!

    1. Hey Irwin, thanks for your comment! You can just create a product-specific coupon and assign it to a single user email if you wish ๐Ÿ™‚

  23. Hi Rodolfo, quick question – is it possible to allow the customer to remove the product from the cart if they so choose as opposed to it simply staying there regardless?

    1. Hey Bri, thanks for your comment! I’m not sure I fully understand your question – can’t a user go to the Cart and remove the item if she wishes?

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. 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 the Business Bloomer Club to get quick WooCommerce support. Thank you!

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