WooCommerce: Implementing Same Category Restriction for Cart Items
In this post, we’ll address your specific requirement of restricting cart items to only include products from the same category in WooCommerce. We’ll analyze your current implementation and provide an optimized solution.
Understanding Your Current Setup
You’re currently using a custom validation filter woocommerce_add_to_cart_validation that checks if new items being added share at least one category with existing cart items. The logic is sound, but there are a few issues:
-
Empty Cart Handling: The current code assumes the cart is not empty when it starts executing. If the cart is empty, it will fail to fetch any product data.
-
Error Display: You’re using
wc_add_noticewhich displays errors at the top of the page. This might not be the most intuitive placement for users adding items to their cart.
Optimizing the Approach
To resolve these issues, we’ll make a few adjustments:
-
Handle Empty Cart: We need to add a check before entering the loop to ensure there are actually products in the cart. If it’s empty, we can skip further processing.
-
Clear Error Message: Let’s remove the previous error notice (if any) before adding new notices for better user experience.
Here’s the optimized version of your function:
function is_product_the_same_cat($valid, $product_id, $quantity) {
global $woocommerce;
// Remove previous notices
wc_clear_notices();
if (empty($woocommerce->cart->get_cart())) {
return true; // No need to process if cart is empty
}
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');
$cat_ids = array_map('intval', wp_list_pluck($terms, 'term_id'));
$target_cat_ids = array_map('intval', wp_list_pluck($target_terms, 'term_id'));
$same_cat = array_intersect($cat_ids, $target_cat_ids);
if (count($same_cat) > 0) {
return $valid;
}
}
wc_add_notice(__('This product is in another category!', 'text-domain'), 'error');
return false;
}
add_filter( 'woocommerce_add_to_cart_validation', 'is_product_the_same_cat', 10, 3 );
Key Changes Made
- We used
wc_clear_notices()to ensure there are no previous error messages. - Added a check for an empty cart before the loop begins.
- Used
wp_list_pluckfor cleaner and more efficient array manipulation.
Conclusion
With these modifications, your function should now work correctly:
- It properly handles adding items from an empty cart.
- The error message is displayed only when necessary and clearly communicates the issue to users.
- The code is cleaner and more performant due to the use of WordPress functions like
wp_list_pluck.
Remember that custom functionality like this might require testing with various themes and plugins to ensure it works seamlessly across different WooCommerce setups.
If you found this solution helpful, feel free to share it or check out our WooCommerce Tutorials for more in-depth guides on customizing your e-commerce store.