根据特定产品有条不紊地删除Woocommerce购物车商品

A specific WooCommerce product can only be by itself in the cart.

So how do I clear the cart while adding this specific product to the cart? and how can I remove this specific product from the cart when adding any other product?

I've figured out how to empty the cart when adding a specific product but I don't know how to remove this specific product from the cart when adding any other product.

The following will remove conditionally cart items based on a specific product:

  • When the specific product is added to cart, all other items are removed.
  • When any other product is added to cart, it removes the specific product (if it's in cart)

Here is the code:

// Remove conditionally cart items based on a specific product (item)
add_action( 'woocommerce_before_calculate_totals', 'remove_cart_items_conditionally', 10, 1 );
function remove_cart_items_conditionally( $cart ) {
    // HERE define your specific product ID
    $specific_product_id = 37; 

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $cart_items  = $cart->get_cart(); // Cart items array
    $items_count = count($cart_items); // Different cart items count

    // Continue if cart has at least 2 different cart items
    if ( $items_count < 2 )
        return;

    $last_item    = end($cart_items); // Last cart item data array
    $is_last_item = false; // Initializing

    // Check if the specific product is the last added item
    if ( in_array($specific_product_id, array( $last_item['product_id'], $last_item['variation_id'] ) ) ) {
        $is_last_item = true;
    }

    // Loop through cart items
    foreach ( $cart_items as $cart_item_key => $cart_item ) {
        // Remove all others cart items when specific product ID is the last added to cart
        if ( ! in_array($specific_product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) && $is_last_item ) {
            $cart->remove_cart_item( $cart_item_key );
        }
        // Remove the specific item when its is not the last added to cart
        elseif ( in_array($specific_product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) && ! $is_last_item ) {
            $cart->remove_cart_item( $cart_item_key );
        }
    }
}

Code goes on function.php file of your active child theme (or active theme). Tested and works.

The above works perfectly! You can also add a notice to the cart once items have been removed to help with the user experience. Add this to the // Loop through cart items section in the first if statement:

wc_add_notice( __( 'Product XYZ has been removed from your cart because...', 'theme_domain' ), 'notice' );