Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Remove cross sell products as well when removing the main product in woo commerce
add_action( 'woocommerce_cart_item_removed', function ( $cart_item, $cart ) {
$product_id_cart_item_pairs = WC()->session->get( 'product_id_cart_item_pairs', array() );
$cart_item_product_pairs = WC()->session->get( 'cart_item_product_pairs', array() );
// Get the product ID using session store
$product_id = isset( $product_id_cart_item_pairs[ $cart_item ] ) ? $product_id_cart_item_pairs[ $cart_item ] : false;
if ( ! $product_id ) {
return;
}
//get product cross sell products
$product = wc_get_product( $product_id );
//If this is variation product
if ( $product->get_type() == 'variation' ) {
$main_product = wc_get_product( $product->get_parent_id() );
} else {
$main_product = $product;
}
$cross_sell_products = $main_product->get_cross_sell_ids();
if ( ! empty( $cross_sell_products ) ) {
foreach ( $cross_sell_products as $cross_sell_product_id ) {
//Get cart item Key
$cross_sell_product_cart_item_key = $cart_item_product_pairs[ $cross_sell_product_id ];
if ( WC()->cart->find_product_in_cart( $cross_sell_product_cart_item_key ) ) {
WC()->cart->remove_cart_item( $cross_sell_product_cart_item_key );
}
}
}
}, 99, 2 );
add_action( 'woocommerce_add_to_cart', function ( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
$product_id_cart_item_pairs = WC()->session->get( 'product_id_cart_item_pairs', array() );
$cart_item_product_pairs = WC()->session->get( 'cart_item_product_pairs', array() );
if ( $variation_id > 0 ) {
$product_id_cart_item_pairs[ $cart_item_key ] = $variation_id;
$cart_item_product_pairs[ $variation_id ] = $cart_item_key;
} else {
$product_id_cart_item_pairs[ $cart_item_key ] = $product_id;
$cart_item_product_pairs[ $product_id ] = $cart_item_key;
}
WC()->session->set( 'product_id_cart_item_pairs', $product_id_cart_item_pairs );
WC()->session->set( 'cart_item_product_pairs', $cart_item_product_pairs );
}, 99, 6 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.