I have a question abt woocommerce add to cart validation. Basically what I want the code to do is to check if there is more than one item for product category (ID: 56) when product category (ID: 55) exists. And only crosscheck against 2 role: “non logged in users”, “Customers”.
For you information, i didn’t write this code, i used Chatgpt to get the code, because I don’t know how to code
Your help is very much appreciated, thanks
The code is in the following:
function custom_add_to_cart_validation($passed, $product_id, $quantity) {
// Get the current user's role
$current_user_role = wp_get_current_user()->roles[0];
// Check if the user is not logged in or has the role "Customers"
if (!is_user_logged_in() || $current_user_role == 'Customers') {
// Get the product categories
$product_categories = get_the_terms( $product_id, 'product_cat' );
$product_cat_ids = wp_list_pluck( $product_categories, 'term_id' );
// Check if the product belongs to the "restricted" category (category y)
if (in_array(56, $product_cat_ids)) {
// Get the cart items
$cart_items = WC()->cart->get_cart();
// Check if there is at least one item from the "required" category (category x) in the cart
$has_required_item = false;
foreach ($cart_items as $cart_item) {
$item_categories = get_the_terms( $cart_item['product_id'], 'product_cat' );
$item_cat_ids = wp_list_pluck( $item_categories, 'term_id' );
if (in_array(55, $item_cat_ids)) {
$has_required_item = true;
break;
}
}
// If there is at least one item from the "required" category in the cart, check if there is already an item from the "restricted" category in the cart
if ($has_required_item) {
$restricted_count = 0;
foreach ($cart_items as $cart_item) {
$item_categories = get_the_terms( $cart_item['product_id'], 'product_cat' );
$item_cat_ids = wp_list_pluck( $item_categories, 'term_id' );
if (in_array(56, $item_cat_ids)) {
$restricted_count += $cart_item['quantity'];
}
}
// If there is already an item from the "restricted" category in the cart, return false to prevent the item from being added to the cart
if ($restricted_count > 1) {
wc_add_notice(__('You can only have one item from Smart Device category in the cart if you added any Membership Plan.', 'woocommerce'), 'error');
$passed = false;
}
}
}
}
return $passed;
}
add_filter('woocommerce_add_to_cart_validation', 'custom_add_to_cart_validation', 10, 3);
I am hoping someone to point out what i should change on the code
3