I have a function that checks if products are in the same category and then if true it allows this product to be added to cart.
If a product does not pass validation I want notification or alert appear(This product in a different category). I do not know how to implement this. Could you please give me some advice.
add_filter('nav_menu_css_class', 'atg_menu_classes', 1, 3);
function is_product_the_same_cat($valid, $product_id, $quantity) {
global $woocommerce;
if($woocommerce->cart->cart_contents_count == 0){
return true;
}
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' );
foreach ($terms as $term) {
$cat_ids[] = $term->term_id;
}
foreach ($target_terms as $term) {
$target_cat_ids[] = $term->term_id;
}
}
$same_cat = array_intersect($cat_ids, $target_cat_ids);
if(count($same_cat) > 0) return $valid;
else {
wp_safe_redirect(get_permalink( get_page_by_path( 'about' ) ) );
exit();;
}
}
add_filter( 'woocommerce_add_to_cart_validation', 'is_product_the_same_cat',10,3);