I have a woocommerce site I use the booster plugin to enable sold individually for each product but now I want to sold individually for each category and if someone add a product to cart on a category then can not add another product of that category to cart
2
votes
2 Answers
1
votes
In the code below there is 2 functions:
- The 1st one is a conditional function checking categories in cart items
- The 2nd one will avoid add to cart when a product category already exist in cart items and will display a custom message.
The code:
// Conditional function: Checking product categories in cart items
function check_cats_in_cart( $product_id ) {
$taxonomy = 'product_cat';
$has_term = true;
foreach( WC()->cart->get_cart() as $item ){
foreach( wp_get_post_terms( $item['product_id'], $taxonomy ) as $term ){
// Allowing add to cart the same product
if( has_term( $term->slug, $taxonomy, $product_id ) ){
$has_term = false;
break; // stops the 2nd loop
}
}
// Allowing the same product to be added (not activated. you can uncomment lines below)
# if ( $item['product_id'] == $product_id )
# $has_term = true;
if( $has_term )
break; // stops the 1st loop
}
return $has_term;
}
// Avoid add to cart when a product category already exist in cart items, displaying a custom error message
add_filter( 'woocommerce_add_to_cart_validation', 'sold_individually_by_cats_valid', 10, 3 );
function sold_individually_by_cats_valid( $passed, $product_id, $quantity) {
$passed = check_cats_in_cart( $product_id );
if( ! $passed ){
// Displaying a custom message
$message = __("This product category is already in cart. Try another product", "woocommerce");
wc_add_notice( $message, 'error' );
}
return $passed;
}
Code goes in function.php file of the active child theme (or active theme).
Tested and works.
If you want to allow adding to cart again the same product (that increases only the quantity of an existing product), you will uncomment this code in the function:
if ( $item['product_id'] == $product_id )
$has_term = true;
0
votes
You can try it this one
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 {
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);
I found it from here