Woocommerce only one product per category in cart, last product added must stay in cart

On this Stack-O page 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!

Read more here: Woocommerce only one product per category in cart, last product added must stay in cart

Leave a Reply

Your email address will not be published. Required fields are marked *