Inthujan Kantharuban
Inthujan Kantharuban

Reputation: 33

Woocommerce change quantity min limit for each product in cart

I have couple of products that can only be bought if min quantity is over certain number.

I wrote and put a snippet of code in my child themes functions.php to change the min quantity for products.

function wpa116693_filter_min_quantity( $min, $product ){

    if ( has_term ( '5', 'product_tag' ) ){
        return 5;
    }

    if ( has_term ( '10', 'product_tag' ) ){
        return 10;
    }

    if ( has_term ( '6', 'product_tag' ) ){
        return 6;
    }
}
add_filter( 'woocommerce_quantity_input_min', 'wpa116693_filter_min_quantity', 10, 2 );

So what it does is, if it finds a product with the tag 5 then it will change the quantity min to 5. this works in single product page but it doesn't work in cart page. I can go lower than the min quantity in the cart page. I believe it doesn't work because "has_term" does not work in the cart page.

I want it to work in cart page too. Please help me solve this, thank you.

Upvotes: 0

Views: 2669

Answers (1)

Raunak Gupta
Raunak Gupta

Reputation: 10809

You need to hook your function to woocommerce_cart_loaded_from_session like this:

add_action('woocommerce_cart_loaded_from_session', 'wh_checkAndUpdateCart');

function wh_checkAndUpdateCart()
{

    //if the cart is empty do nothing
    if (WC()->cart->get_cart_contents_count() == 0)
    {
        return;
    }

    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item)
    {
        $product_id = $cart_item['product_id']; // Product ID
        $product_qty = $cart_item['quantity']; // Product quantity

        if (has_term(5, 'product_tag', $product_id) && ($product_qty > 5))
        {
            WC()->cart->set_quantity($cart_item_key, 5);
        }
        if (has_term(10, 'product_tag', $product_id) && ($product_qty > 10))
        {
            WC()->cart->set_quantity($cart_item_key, 10);
        }
        if (has_term(6, 'product_tag', $product_id) && ($product_qty > 6))
        {
            WC()->cart->set_quantity($cart_item_key, 6);
        }
    }
}

Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
Code is tested and works.

Hope this helps!

Upvotes: 2

Related Questions