Skip to content

Instantly share code, notes, and snippets.

@prasidhda
Last active November 27, 2019 07:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save prasidhda/81973fe18bff3fab6de1da83ca24d5db to your computer and use it in GitHub Desktop.
Save prasidhda/81973fe18bff3fab6de1da83ca24d5db to your computer and use it in GitHub Desktop.
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