Hello,
I am trying to make two so different categories of products, that I don’t want them to be purchased at the same time.
What I would like to happen is if there is a product from one category is in the cart already, then products from another can not be added to the cart.
Of course, only the parent category should be considered.
I was trying to use the following code, but it is not working. As I understand it is for an older version of woocommerce.
Code:
function is_product_the_same_cat($valid, $product_id, $quantity) {
global $woocommerce;
// start of the loop that fetches the cart items
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values[‘data’];
$terms = get_the_terms( $_product->id, ‘product_cat’ );
$target_terms = get_the_terms( $product_id, ‘product_cat’ ); //get the current items
foreach ($terms as $term) {
$cat_ids[] = $term->term_id; //get all the item categories in the cart
}
foreach ($target_terms as $term) {
$target_cat_ids[] = $term->term_id; //get all the categories of the product
}
}
$same_cat = array_intersect($cat_ids, $target_cat_ids); //check if they have the same category
if(count($same_cat) > 0) return $valid;
else {
wc_add_notice( ‘This product is in another category!’, ‘error’ );
return false;
}
}
add_filter( ‘woocommerce_add_to_cart_validation’, ‘is_product_the_same_cat’,10,3
Hey zeaigars,
You might want to address this question to the WooCommerce support here
If you need further assistance please let us know.
Best regards,
Victoria