Woocommerce 将购物车限制为四种选择中的一种 I have this code that works great for 2 products if one is added the other is removed. But I would like to add 4

Woocommerce 将购物车限制为四种选择中的一种 I have this code that works great for 2 products if one is added the other is removed. But I would like to add 4,woocommerce,product-quantity,limiting,Woocommerce,Product Quantity,Limiting,将购物车限制为四种选择中的一种 I have this code that works great for 2 products if one is added the other is removed. But I would like to add 4 products to the category. Only one can be in the cart, if one is in the cart and the customer changes mind and wants a d

将购物车限制为四种选择中的一种 I have this code that works great for 2 products if one is added the other is removed. But I would like to add 4 products to the category. Only one can be in the cart, if one is in the cart and the customer changes mind and wants a different one (from these 4 products) the one in the cart will be removed and the new choice added. Notices are not important. Any help very much appreciated.
add_action( 'woocommerce_add_to_cart', 'check_product_added_to_cart', 10, 6 );
function check_product_added_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {

    // Set HERE your targeted product ID

    $target_product_ids1 = array(391);
    $target_product_ids2 = array(393);
    // Set HERE the  product ID to remove
    $item_id_to_remove1 = 393;
    $item_id_to_remove2 = 391;

    // Initialising some variables
    $has_item1 = $has_item2 = $is_product_id1 = $is_product_id2 = false;

    foreach( WC()->cart->get_cart() as $key => $item ){
        // Check if the item to be removed 1 is in cart
        if( $item['product_id'] == $item_id_to_remove1 ){
            $has_item1 = true;
            $key_to_remove1 = $key;
        }
        // Check if the item to be removed 2 is in cart
        if( $item['product_id'] == $item_id_to_remove2 ){
            $has_item2 = true;
            $key_to_remove2 = $key;
        }

        // Check if we added to cart any targeted product IDs 1
        if( in_array( $product_id, $target_product_ids1 ) ){
            $is_product_id1 = true;
        }

        // Check if we added to cart any targeted product IDs 2
        if( in_array( $product_id, $target_product_ids2 ) ){
            $is_product_id2 = true;
        }
    }

    if( $has_item1 && $is_product_id1 ){
        WC()->cart->remove_cart_item($key_to_remove1);

        // Optionaly displaying a notice for the removed item:
        wc_add_notice( __( 'The product 1 "blab bla" has been removed from cart.', 'theme_domain' ), 'notice' );
    }

    if( $has_item2 && $is_product_id2 ){
        WC()->cart->remove_cart_item($key_to_remove2);

        // Optionaly displaying a notice for the removed item:
        wc_add_notice( __( 'The product 2 "blab bla" has been removed from cart.', 'theme_domain' ), 'notice' );
    }
}