I am using the code below to remove other WooCommerce product category items from the cart when there is an item with a special product category \'cat_x\' added in cart and
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'] )) {
I just tried and i got a syntax error the array that i fixed this way:
$terms_slugs = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'slugs'));
just a comma after product_cat distraction, but maybe somebody would need it.