Home » WooCommerce: Add Product to Cart On Visit Programmatically

WooCommerce: Add Product to Cart On Visit Programmatically

by Tutor Aspire

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 tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 3.9
 * @donate $9     https://tutoraspire.com
 */
  
add_action( 'template_redirect', 'tutoraspire_add_product_to_cart_automatically' );
  
function tutoraspire_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 );
   }
    
}

You may also like