Skip to content

Instantly share code, notes, and snippets.

@10horizons
Last active February 5, 2021 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 10horizons/045e103ea810f4b739704bf521538d75 to your computer and use it in GitHub Desktop.
Save 10horizons/045e103ea810f4b739704bf521538d75 to your computer and use it in GitHub Desktop.
Prevent upsell product from being purchased on its own
<?php
function thp_remove_upsell ($cart) {
$main_product_ID = 38; //CHANGE TO THE MAIN PRODUCT ID
$upsell_product_ID = 39; //CHANGE TO YOUR UPSELL PRODUCT ID
$has_main_product = false;
$has_upsell = false;
foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item['product_id'] == $main_product_ID ) {
$has_main_product = true;
}
else if ( $cart_item['product_id'] == $upsell_product_ID ) {
$has_upsell = true;
$upsell_cart_key = $cart_item_key;
}
}
if ( $has_upsell && !$has_main_product ) {
$cart->remove_cart_item( $upsell_cart_key );
}
}
add_action( 'woocommerce_before_calculate_totals', 'thp_remove_upsell' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment