Allow only one product per product category in the cart

In this Question / Answer, I found PHP code on how to simply add one product per category to cart in Woocommerce.

The code works very well, but I want to add the last added item to the cart, and if there is already a product in this category in the cart, I want the old one to be removed.

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;
}

      

This is a code snippet that comes from LoicTheAztec . It works great, but I need an additional option ...

There are 5 different categories in my Woocommerce, there is only basket space for one item per category. The last added item must remain, an item of the same category that is already in the cart must be removed from the cart. Do any of you have a solution?

Many thanks!

+1


source to share


1 answer


Here is your world of code that will remove the cart item that the product category belongs to with the current product category.

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) {

    // Getting the product categories slugs in an array for the current product
    $product_cats_object = get_the_terms( $product_id, 'product_cat' );
    foreach($product_cats_object as $obj_prod_cat)
        $product_cats[] = $obj_prod_cat->slug;

    // Iterating through each cart item
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ){

        // When the product category of the current product match with a cart item
        if( has_term( $product_cats, 'product_cat', $cart_item['product_id'] ))
        {
            // Removing the cart item
            WC()->cart->remove_cart_item($cart_item_key);

            // Displaying a message
            wc_add_notice( 'Only one product from a category is allowed in cart', 'notice' );

            // We stop the loop
            break;
        }
    }
    return $passed;
}

      



This code is found in the function.php file of your active child theme (or theme), as well as any plugin file.

This code has been tested and works for WooCommerce version 2.6+ and 3.0+

+1


source







All Articles