2
votes

I am using woocommerce and stuck in a situation.

I have 4 different products with IDs 1, 2, 3 and 4.

What I need is that customer can add any 1 of the 4 items in cart at a time. For instance, if item 3 is in the cart then item 4 or 1 or 2 cannot be added to the cart.

How do I get this in Woocommerce?

Any help is appreciated.

1

1 Answers

0
votes

Updated: Try this, it should avoid, for defined product Ids, adding to cart when a another targeted product already exist in cart items, displaying a custom error message:

add_filter( 'woocommerce_add_to_cart_validation', 'conditional_product_in_cart', 10, 3 );
function conditional_product_in_cart( $passed, $product_id, $quantity) {

    // HERE define your 4 specific product Ids
    $products_ids = array( 37, 40, 47, 53 );

    // Searching in cart for IDs
    if ( ! WC()->cart->is_empty() )
        foreach( WC()->cart->get_cart() as $cart_item ){
            $item_pid = $cart_item['product_id'];
            // If current product is from the targeted IDs and a another targeted product id in cart
            if( in_array( $item_pid, $products_ids ) && in_array( $product_id, $products_ids ) && $product_id != $item_pid ){
                $passed = false; // Avoid add to cart
                break; // Stop the loop
            }
        }

    if ( ! $passed ){
        // Displaying a custom message
        $message = __("You can only have one product in cart at the time.", "woocommerce");
        wc_add_notice( $message, 'error' );
    }
    return $passed;
}

Code goes in function.php file of the active child theme (or active theme).

Tested and works