Problem
Do not allow customer add products from other categories if a product from a specific category is add or in the cart.
This code will check for parent product categories, so for a defined product category, it will:
- Avoid adding to cart other product categories when the defined category is in cart.
- It will remove cart items from other product categories when a product from the defined category is added to cart.
Solution
Adding this code to your child theme’s functions.php file.
//Dont allow other products if product from category X are in the cart
// Custom conditional function that checks for parent product categories
function has_parent_term( $product_id ) {
// HERE set your targeted product category SLUG
$category_slug = 'beerservice'; // <==== <==== <==== <==== <==== <==== <====
// Convert category term slug to term id
$category_id = get_term_by('slug', $category_slug, 'product_cat')->term_id;
$parent_term_ids = array(); // Initializing
// Loop through the current product category terms to get only parent main category term
foreach( get_the_terms( $product_id, 'product_cat' ) as $term ){
if( $term->parent > 0 ){
$parent_term_ids[] = $term->parent; // Set the parent product category
} else {
$parent_term_ids[] = $term->term_id;
}
}
return in_array( $category_id, $parent_term_ids );
}
// Avoid add to cart others product categories when "beerservice" is in cart
add_filter( 'woocommerce_add_to_cart_validation', 'specific_category_avoid_add_to_cart_others', 20, 3 );
function specific_category_avoid_add_to_cart_others( $passed, $product_id, $quantity) {
if( WC()->cart->is_empty() || has_parent_term( $product_id ) ) {
return $passed;
}
foreach( WC()->cart->get_cart() as $cart_item ){
if( has_parent_term( $cart_item['product_id'] ) ) {
wc_add_notice( __('Alert message 1 (avoid add to cart)', 'woocommerce' ), 'error' ); // Display a custom error notice
return false; // Avoid add to cart
}
}
return $passed;
}
// Remove other items when our specific product is added to cart
add_action( 'woocommerce_add_to_cart', 'conditionally_remove_other_products', 20, 4 );
function conditionally_remove_other_products ( $cart_item_key, $product_id, $quantity, $variation_id ){
if( has_parent_term( $product_id ) ) {
foreach( WC()->cart->get_cart() as $item_key => $cart_item ){
if( ! has_parent_term( $cart_item['product_id'] ) ) {
WC()->cart->remove_cart_item( $item_key );
wc_add_notice( __('Alert message 2 (Item removed from cart)', 'woocommerce' ), 'error' ); // Display a custom error notice
}
}
}
}