'Set custom quantity arguments to products from specific category in WooCommerce

i'm trying to set a minimum order quantity for a specific category in my woocommerce store. I've written a piece of code but it seems like the minimum quantity in the cart applies to ALL categories and not only to the one i've set up ("nettoyage") ... What did i do wrong ?

Here's my code (from my functions.php) :

add_filter('woocommerce_quantity_input_args', 'bloomer_woocommerce_quantity_changes', 10, 2);

function bloomer_woocommerce_quantity_changes($args, $product)
{
    if (!is_cart()) {
        if (is_singular('product') && (has_term('nettoyage', 'product_cat'))) {

            $args['input_value'] = 3; // Start from this value (default = 1)
            $args['max_value'] = 10; // Max quantity (default = -1)
            $args['min_value'] = 3; // Min quantity (default = 0)
            $args['step'] = 1; // Increment/decrement by this value (default = 1)

        }
    }

    return $args;
}

function sww_check_category_for_minimum()
{
    // set the minimum quantity in the category to purchase
    $min_quantity = 3;

    // set the id of the category for which we're requiring a minimum quantity
    $category_id = 40;

    // get the product category
    $product_cat = get_term($category_id, 'product_cat');
    $category_name = '<a href="' . get_term_link($category_id, 'product_cat') . '">' . $product_cat->name . '</a>';

    // get the quantity category in the cart
    $category_quantity = sww_get_category_quantity_in_cart($category_id);

    if ($category_quantity < $min_quantity) {
        // render a notice to explain the minimum
        wc_add_notice(sprintf('You must order at least 3 products from the %2$s category to be able to order!', $min_quantity, $category_name), 'error');
    }
}
add_action('woocommerce_check_cart_items', 'sww_check_category_for_minimum');

//Returns the quantity of products from a given category in the WC cart
function sww_get_category_quantity_in_cart($category_id)
{
    // get the quantities of cart items to check against
    $quantities = WC()->cart->get_cart_item_quantities();

    // start a counter for the quantity of items from this category
    $category_quantity = 0;

    // loop through cart items to check the product categories
    foreach ($quantities as $product_id => $quantity) {

        $product_categories = get_the_terms($product_id, 'product_cat');

        // check the categories for our desired one
        foreach ($product_categories as $category) {

            // if we find it, add the line item quantity to the category total
            if ($category_id === $category->term_id) {
                $category_quantity += $quantity;
            }
        }
    }

    return $category_quantity;
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source