Posted on

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.4.3
 */
 
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 code?

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 delicate files - if you need more guidance, please take a look at my free WooCommerce Customization video tutorial.

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?

Check out these free videos, tutorials and tips!

  • how-to-edit-woocommerce-with-php-snippets
  • woocommerce-hooks-add_action-list-visual
  • woocommerce-customize-single-product-page-PHP
  • woocommerce-customize-shop-page-PHP
  • woocommerce-advanced-customization
  • how-to-edit-woocommerce-cart
  • woocommerce-customize-checkout-page-PHP
  • woocommerce-email-customization
  • woocommerce-conditional-logic

Rodolfo Melogli

Author, WooCommerce expert, WordCamp speaker and Internet marketer, Rodolfo Melogli has worked as a WooCommerce freelancer since 2011. He helps entrepreneurs and developers overcome their WooCommerce nightmares :) Rodolfo is the organiser of WordCamp Dublin, the Dublin WooCommerce Meetup, the Dublin Ecommerce Meetup and the Dublin WordPress Meetup. He enjoys interacting with people, travelling and chasing tennis & soccer balls. Of course, he loves pizza too.

18 thoughts on “WooCommerce: Add Product to Cart Programmatically

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

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

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

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

  5. 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
    http://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

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

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

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

  9. 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're writing code, please wrap it between: [php] code_here [/php]

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.