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