When running marketing campaigns or BOGO “Buy One Get One” promotions, store owners may create specific 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.
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.
- 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.
- 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.
Alternatively, you can also create a free sample for every purchase on the WooCommerce Product page just with a click of the “Order a Free Product” button.