WooCommerce: Add Product to Cart Programmatically

Quite an interesting functionality! a WooCommerce client required to have the cart pre-filled with one product as soon as the customer 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. Let’s see how this snippet works!

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

Snippet: Add Product to WooCommerce Cart Programmatically

 * @snippet       Add Product to WooCommerce Cart Programmatically
 * @how-to        Watch tutorial @ https://businessbloomer.com/?p=19055
 * @sourcecode    https://businessbloomer.com/?p=19117
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.5.3
 * @donate $9     https://businessbloomer.com/bloomer-armada/
add_action( 'template_redirect', 'bbloomer_add_product_to_cart' );
function bbloomer_add_product_to_cart() {
// select ID
$product_id = 21874;
//check if product already in cart
if ( WC()->cart->get_cart_contents_count() == 0 ) {

// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );

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.

24 thoughts on “WooCommerce: Add Product to Cart Programmatically

  1. Salve,

    vorrei che la quantitΓ  del prodotto inserito partisse da zero e non da uno Γ¨ possibile?
    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 πŸ™‚

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

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

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

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

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

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

  8. 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: http://yourdomain.com/?add-to-cart=25&price=100&custom_reference=REF001
    cart item 2: http://yourdomain.com/?add-to-cart=25&price=990&custom_reference=REF002
    cart item 3: http://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

    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

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


    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

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

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

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