Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Garconis/efcf99c84757ea6bf0801794ec3eeb4d to your computer and use it in GitHub Desktop.
Save Garconis/efcf99c84757ea6bf0801794ec3eeb4d to your computer and use it in GitHub Desktop.
WooCommerce | Limit one product per specific category in the cart at a time
<?php
// https://www.proy.info/woocommerce-allow-only-1-product-per-category/
// Allow only one(or pre-defined) product per category in the cart
// Alternatively, try plugin: https://wordpress.org/plugins/woo-cart-limit/
add_filter( 'woocommerce_add_to_cart_validation', 'allowed_quantity_per_category_in_the_cart', 10, 2 );
function allowed_quantity_per_category_in_the_cart( $passed, $product_id) {
$max_num_products = 1;// change the maximum allowed in the cart
$running_qty = 0;
$restricted_product_cats = array();
//Restrict particular category/categories by category slug
$restricted_product_cats[] = 'events';
//$restricted_product_cats[] = 'cat-slug-two';
// Getting the current product category slugs in an array
$product_cats_object = get_the_terms( $product_id, 'product_cat' );
foreach($product_cats_object as $obj_prod_cat) $current_product_cats[]=$obj_prod_cat->slug;
// Iterating through each cart item
foreach (WC()->cart->get_cart() as $cart_item_key=>$cart_item ){
// Restrict $max_num_products from each category
// if( has_term( $current_product_cats, 'product_cat', $cart_item['product_id'] )) {
// Restrict $max_num_products from restricted product categories
if( array_intersect($restricted_product_cats, $current_product_cats) && has_term( $restricted_product_cats, 'product_cat', $cart_item['product_id'] )) {
// count(selected category) quantity
$running_qty += (int) $cart_item['quantity'];
// More than allowed products in the cart is not allowed
if( $running_qty >= $max_num_products ) {
wc_add_notice( sprintf( 'You can only register %s '.($max_num_products>1?'people':'person').' at a time for events. If you need to register another person for this event, please complete the payment process first — then come back.', $max_num_products ), 'error' );
$passed = false; // don't add the new product to the cart
// We stop the loop
break;
}
}
}
return $passed;
}
@benjaminmateev
Copy link

Hello, how would you change the code to only one product (but as many as you like of it) per category in the cart?

So example, product category food has two products ham and cheese. The visitor can put 5 cheese in the cart or 3 ham but not cheese and ham at the same time in cart. But if there is another category drinks with products you could do 5 cheese and 2 water.

@janzikmund
Copy link

janzikmund commented Apr 7, 2020

Thanks for sharing, helped me a lot. There is just a bug when adding the product for the first time. As your code loops through existing cart items, so only if there already is some item from restricted category, it can bail out. But when your cart is empty, you can easily add 99 products on the first add. See my fixed variant (implemented as a plugin in class):

<?php
/**
 * Plugin Name: Limit Sanitisers Amount
 * Version: 1.1
 * Description: Limit number of products from Hand Sanitiser category that can be added to a single order
 */

HydrochemValidateQty::init();

class HydrochemValidateQty
{
    const ALLOWED_QTY = 6;
    const RESTRICTED_CATEGORIES = ['hand-sanitisers'];

    /**
     * Init
     */
    public static function init()
    {
        self::validateQuantity();
    }

    /**
     * Validate quantity when adding products to cart
     */
    protected static function validateQuantity()
    {
        add_filter( 'woocommerce_add_to_cart_validation', function( $passed, $product_id, $qty) {
            // Getting the current product category slugs in an array
            $product_cats_object = get_the_terms( $product_id, 'product_cat' );
            foreach($product_cats_object as $obj_prod_cat) {
                $current_product_cats[] = $obj_prod_cat->slug;
            }

            // return if this product is not from restricted category
            if(empty(array_intersect(self::RESTRICTED_CATEGORIES, $current_product_cats))) {
                return $passed;
            }

            // if we are here, existing product is restricted, start running qty from there
            $running_qty = $qty;

            // validate if qty not already over
            if($running_qty >= self::ALLOWED_QTY) {
                self::throwErrorNotice();
                return false;
            }

            // Iterating through each cart item
            foreach (WC()->cart->get_cart() as $cart_item_key=>$cart_item ){
                // Restrict $max_num_products from restricted product categories
                if( has_term( self::RESTRICTED_CATEGORIES, 'product_cat', $cart_item['product_id'] )) {

                    // count(selected category) quantity
                    $running_qty += (int) $cart_item['quantity'];

                    // More than allowed products in the cart is not allowed
                    if( $running_qty > self::ALLOWED_QTY ) {
                        self::throwErrorNotice();
                        return false;
                    }

                }
            }
            return $passed;
        }, 10, 3 );
    }

    /**
     * Throw error notice
     */
    protected static function throwErrorNotice()
    {
        wc_add_notice( sprintf( 'You can only purchase %s '.(self::ALLOWED_QTY > 1 ? 'cartons':'carton').' of this product at a time. Please be considerate to others.',  self::ALLOWED_QTY ), 'error' );
    }
}

@hitec4ever
Copy link

This doesn't seem to work when I change the quantity to 1. I'm not able to add a product to the cart anymore. And how can I add a 2nd category? I need to have the situation where the customer can select 1 product per category wit max 2 products in the cart.

@emmavelazquez
Copy link

Hello, can you show us how to limit the user to purchase whatever they like from one single category?

@hitec4ever
Copy link

Hello, can you show us how to limit the user to purchase whatever they like from one single category?

I bought this plugin since all of the code I found didn't work: https://stephensherrardplugins.com/plugins/woocommerce-user-role-minimums/

@andystent
Copy link

andystent commented Apr 25, 2021

If you are using "/checkout/?add-to-cart=id" (as opposed to /cart...) and having the product added twice, try adding this to your functions.php file:

`add_filter( 'woocommerce_add_to_cart_redirect', 'bbloomer_redirect_checkout_add_cart' );

function bbloomer_redirect_checkout_add_cart() {
return wc_get_checkout_url();
}`

I needed to bypass the cart so this works for me. Good luck!

Reference: https://www.businessbloomer.com/woocommerce-redirect-checkout-add-cart/

@morgan-web-development
Copy link

morgan-web-development commented Nov 9, 2021

This doesn't seem to work when I change the quantity to 1. I'm not able to add a product to the cart anymore. And how can I add a 2nd category? I need to have the situation where the customer can select 1 product per category wit max 2 products in the cart.

So if you change the quantity validation from >= to > it will work

// validate if qty not already over if($running_qty > self::ALLOWED_QTY) { self::throwErrorNotice(); return false; }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment