On this Question / Answer I have found the PHP code about how to just add one product per category in cart in Woocommerce.
The code works just fine, but I want to add the latest added product to cart and if there is already a product of that category in the cart, I want to have the oldest deleted.
add_filter( 'woocommerce_add_to_cart_validation', 'custom_checking_product_added_to_cart', 10, 3 );
function custom_checking_product_added_to_cart( $passed, $product_id, $quantity) {
// HERE Type your alert displayed message
// $message = __( 'BLA BLA YOUR MESSAGE.', 'woocommerce' );
$product_cats_object = get_the_terms( $product_id, 'product_cat' );
foreach($product_cats_object as $obj_prod_cat){
$product_cats[] = $obj_prod_cat->slug;
}
foreach (WC()->cart->get_cart() as $cart_item ){
if( has_term( $product_cats, 'product_cat', $cart_item['product_id'] )) {
$passed = false;
wc_add_notice( $message, 'error' );
break;
}
}
return $passed;
}
It is a piece of code that comes from LoicTheAztec . It works fine but I need an extra option...
In my Woocommerce there are 5 different categories, there is just place in the cart for one item per category. The latest added item should stay, the item of the same category that is already in cart must be removed from cart. Does someone of you has a solution?
Many thanks!
Here is your peace of code that will remove a cart item which product category match with the current product category.
This code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works for WooCommerce version 2.6+ and 3.0+