Making a custom function hooked in woocommerce_add_to_cart_validation filter hook is going to do the job in a much more simpler way, without any need to set an array of categories.
So your code will be much more faster and compact. Additionally you can display a custom notice to warn the customer.
This code will avoid adding to cart, if an item of a different category is in cart:
add_filter( 'woocommerce_add_to_cart_validation', 'add_to_cart_validation_callback', 10, 3 );
function add_to_cart_validation_callback( $passed, $product_id, $quantity) {
// HERE set your alert text message
$message = __( 'MY ALERT MESSAGE.', 'woocommerce' );
if( ! WC()->cart->is_empty() ) {
// Get the product category terms for the current product
$terms_slugs = wp_get_post_terms( $product_id, 'product_cat' array('fields' => 'slugs'));
// Loop through cart items
foreach (WC()->cart->get_cart() as $cart_item ){
if( ! has_term( $terms_slugs, 'product_cat', $cart_item['product_id'] )) {
$passed = false;
wc_add_notice( $message, 'error' );
break;
}
}
}
return $passed;
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and it works
Restricting cart items to be only from different product categories:
Replace in the function the condition:
if( ! has_term( $product_cats, 'product_cat', $cart_item['product_id'] )) {
by
if( has_term( $product_cats, 'product_cat', $cart_item['product_id'] )) {
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…