Skip to content

Instantly share code, notes, and snippets.

@10horizons
Created May 11, 2021 09:34
Show Gist options
  • Save 10horizons/120ba8bd1fcbcc803e4d8b92c7e48d96 to your computer and use it in GitHub Desktop.
Save 10horizons/120ba8bd1fcbcc803e4d8b92c7e48d96 to your computer and use it in GitHub Desktop.
Prevent upsell products from being purchased without the main product
<?php
function thp_remove_upsells ($cart) {
$main_product_ID = 38; //CHANGE TO THE MAIN PRODUCT ID
$upsell_product_IDs = array( 39, 40 ); //CHANGE TO YOUR UPSELL PRODUCT ID's
$upsell_cart_keys = array();
$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;
}
foreach ($upsell_product_IDs as $upsell_product_ID) {
if ( $cart_item['product_id'] == $upsell_product_ID ) {
$has_upsell = true;
$upsell_cart_keys[] = $cart_item_key;
}
}
}
if ( $has_upsell && !$has_main_product ) {
foreach ($upsell_cart_keys as $upsell_cart_key) {
$cart->remove_cart_item( $upsell_cart_key );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'thp_remove_upsells' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment