Looking to boost your WooCommerce store’s average order value?
Upsells are a powerful tool, but manually entering them via the Edit Product page can be tedious.
This tutorial dives into the world of programmatic WooCommerce product upsells, empowering you to leverage code for a dynamic and data-driven upsell strategy.
In under 5 lines of PHP, we’ll guide you through the process of setting up upsells using code, unlocking greater control and personalization for a seamless customer experience that maximizes your sales potential. Enjoy!
PHP Snippet 1: Set The Same Product Upsells For All WooCommerce Products
This is super helpful if you want your products to have the same upsells storewide, and you want to avoid entering upsells manually on each Edit Product page!
/**
* @snippet Programmatically Set Upsells For All WooCommerce Products
* @how-to businessbloomer.com/woocommerce-customization
* @author Rodolfo Melogli, Business Bloomer
* @compatible WooCommerce 9
* @community https://businessbloomer.com/club/
*/
add_filter( 'woocommerce_product_get_upsell_ids', 'bbloomer_same_upsell_ids', 9999, 2 );
function bbloomer_same_upsell_ids( $upsell_ids, $product ) {
return array( 222239, 222166 ); // PRODUCT IDS
}
PHP Snippet 2: Set Upsells For A Single WooCommerce Product
You can of course use the $product argument that the woocommerce_product_get_upsell_ids filter gives us, and define a list of upsell IDs per product.
/**
* @snippet Programmatically Set Upsells For A WooCommerce Product
* @how-to businessbloomer.com/woocommerce-customization
* @author Rodolfo Melogli, Business Bloomer
* @compatible WooCommerce 9
* @community https://businessbloomer.com/club/
*/
add_filter( 'woocommerce_product_get_upsell_ids', 'bbloomer_per_product_upsell_ids', 9999, 2 );
function bbloomer_per_product_upsell_ids( $upsell_ids, $product ) {
if ( $product->get_id() == 1234 ) return array( 222239, 222166 ); // PRODUCT IDS
if ( $product->get_id() == 4567 ) return array( 245687, 245761 ); // PRODUCT IDS
// ETC.
}
This is quite useful Rodolfo. Thank you.
Please add
// Return the fixed upsell IDs
return $fixed_upsell_ids;
It is also possible to check if the product belongs to a specific category and set different upsell IDs accordingly.
Why? I’m already returning an array of product IDs, so I don’t need to return that afterwards.
As per the other question, I suggest you take a look at “conditional logic”: https://businessbloomer.com/woocommerce-conditional-logic-ultimate-php-guide/
Hi,
Thanks for this improvement!
It would indeed be nice to add the same functionality based on categories and upselling categories in case of variable products.
example:
category hats, category belts, category accessories
product A: hats & accessories – upsells hats + accessories
product B : belts & accessories – upsells belts + accessories
Tks
You’re welcome!