When running marketing campaigns or BOGO “Buy One Get One” promotions, store owners may create custom URLs with upsell products to encourage customers to add complementary items to their carts. With this customization, you can automatically add the upsell products to the cart which will entice customers to purchase additional items in your WooCommerce store. Let’s look into how the upsell products are automatically added to the cart!
Solution: Automatically Add Upsell Products to Cart via Custom Link
The provided code works well for adding upsell products to the cart via a URL parameter and the typical URL parameter is as follows: http://yourwebsite.com/?add-upsells-to-cart=PRODUCT_ID
add_action( 'wp_loaded', 'bulk_upsell_add_to_cart_action', 20 ); function bulk_upsell_add_to_cart_action() { if ( ! empty( $_GET['add-upsells-to-cart'] ) ) { $product_id = absint( $_GET['add-upsells-to-cart'] ); $product = wc_get_product( $product_id ); if ( $product ) { $upsell_ids = $product->get_upsells(); if ( $upsell_ids ) { $count = 0; foreach ( $upsell_ids as $upsell_id ) { if ( WC()->cart->add_to_cart( $upsell_id ) ) { $count ++; } } wc_add_notice( sprintf( _n( 'Added %d item to the cart', 'Added %d items to the cart', $count ), $count ) ); } } } }
Output
Let’s look into the product ID=649 and the upsell products linked to it.
- From the WordPress dashboard, go to “WooCommerce” and select “Products.”
- Click on the product for which you want to set upsells. For e.g I’m setting upsells for this specific product shown in the image below.
![How to Automatically Add Upsell Products to Cart via Custom Link in WooCommerce? 1 How to Automatically Add Upsell Products to Cart via Custom Link in WooCommerce? - Tyche Softwares](https://media.tychesoftwares.com/wp-content/uploads/create-upsell-product-1024x371.png)
- On the product editing page, find the “Product Data” section.
- Scroll down to the “Linked Products” tab.
- In the “Upsells” field, start typing and select related products.
![How to Automatically Add Upsell Products to Cart via Custom Link in WooCommerce? 2 How to Automatically Add Upsell Products to Cart via Custom Link in WooCommerce? - Tyche Softwares](https://media.tychesoftwares.com/wp-content/uploads/upsell-products-1024x437.png)
- Save or update the product to apply the upsells.
When a customer clicks on the provided URL containing the product ID 649, the code automatically adds the upsell products associated with this product to the cart.
![How to Automatically Add Upsell Products to Cart via Custom Link in WooCommerce? 3 How to Automatically Add Upsell Products to Cart via Custom Link in WooCommerce? - Tyche Softwares](https://media.tychesoftwares.com/wp-content/uploads/Adding-upsell-products-to-cart-via-URL-1024x590.png)
Just like automatically adding the upsell product to the cart, you can also add a free sample for every purchase on the WooCommerce just with a click of the “Order a Free Product” button.