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 ProgrammaticallyWooCommerce: 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
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
  
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 );
   }
    
}
Share:

Leave a Reply