Home » WooCommerce: Add Product to Cart When Visiting a Specific Page

WooCommerce: Add Product to Cart When Visiting a Specific Page

by Tutor Aspire

We’ve already seen how to add a product to cart automatically when a user enters your website. However, I needed a different functionality on this same website, and specifically I wanted a product added to cart only when a user like you visits a specific WordPress page ID.

If you wish to test, go to my free video tutorial page called “How to Customize the WooCommerce Single Product Page“. As soon as the page loads a product is magically added to cart, so that the WooCommerce Checkout on that same page is populated with the hidden item. If you go to my Cart page right after visiting that landing page, you can verify there is a product in there.

So, how did I do it?

WooCommerce: Add Product to Cart When Visiting a Specific Page ID

WooCommerce PHP Snippet: Add Product to Cart When Visiting a Specific WordPress Page ID

/**
 * @snippet       Add Product to Cart When Visiting Page ID - WooCommerce
 * @how-to        Get tutoraspire.com FREE
 * @sourcecode    https://tutoraspire.com/?p=75861
 * @author        Tutor Aspire
 * @compatible    WooCommerce 3.4.3
 */

add_action( 'wp', 'tutoraspire_add_product_to_cart_on_page_id_load' );
 
function tutoraspire_add_product_to_cart_on_page_id_load() {
         
// product ID to add to cart
$product_id = 21874;

// page ID to target         
if ( is_page( 19473 ) ) {    
WC()->cart->empty_cart();
WC()->cart->add_to_cart( $product_id ); 
}

}

You may also like