Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to set minimum and maximum allowable product quantities to be added in WooCommerce Cart

Are you planning to define the minimum and maximum quantities to the products which you are selling on your store build up with WooCommerce? If yes, then you can achieve your goal simply by using filters available in WooCommerce OR by using some plugins available on WordPress Repository.

First, we will see how to limit the minimum and maximum quantity of products that can be added to WooCommerce cart using the filters in WooCommerce. Below are the two filters which allow you to change the default min and max values for the quantity selector field.

  • woocommerce_quantity_input_min : Allows to change the minimum value for the quantity. Default value is 0.
  • woocommerce_quantity_input_max : Allows to change the maximum value for the quantity. Default value is -1.
/*
* Changing the minimum quantity to 2 for all the WooCommerce products
*/

function woocommerce_quantity_input_min_callback( $min, $product ) {
	$min = 2;  
	return $min;
}
add_filter( 'woocommerce_quantity_input_min', 'woocommerce_quantity_input_min_callback', 10, 2 );

/*
* Changing the maximum quantity to 5 for all the WooCommerce products
*/

function woocommerce_quantity_input_max_callback( $max, $product ) {
	$max = 5;  
	return $max;
}
add_filter( 'woocommerce_quantity_input_max', 'woocommerce_quantity_input_max_callback', 10, 2 );

So paste the above code snippet in your currently active theme’s functions.php file and visit the front end of the WooCommerce product page. You will be able to select quantity only between 2 to 5 for that item.

Minimum and Maximum allowed quantity - set minimum and maximum quantities in WooCommerce
Minimum and Maximum allowed quantity

The above solution will only work on the WooCommerce product page. Which means, even after placing above code snippet in functions.php file, the customer can update the quantity on Cart page. Also, it will be applied to all the product available on your store.

To correct it, this will need some validations and some options where store owner can set the values to minimum and maximum quantity for the product.

So let’s create these options on the Product Meta box so that you can set this quantity for each product separately. And based on the values set to these options we can perform validations on the Cart page.

Where to Add Custom Code in WooCommerce?

In WordPress, adding the custom code can be done using the Theme Editor or via the Code Snippets plugin. Let’s see the steps on where to place the code.

1. Theme Editor:

  • Navigate to Appearance > Theme Editor in your WordPress dashboard.
  • Select the functions.php file from the list of theme files.
  • Carefully insert the code snippet at the end of the file.
  • Click the “Update File” button to apply the modifications.

2. Code Snippets Plugin:

  • Go to Plugins > Add New and search for “Code Snippets.” Install a plugin called “Code Snippets” and activate it.
  • Navigate to Snippets in your dashboard and click “Add New.”
  • Paste the code snippet into the provided code editor. 
  • Give your snippet a descriptive title and click the “Save Changes and Activate” button.

Before implementing the code snippets, we need to find the ID of the particular variable product, so here are the steps as mentioned below.

  • Navigate to Products > All Products.
  • After redirecting to the product page, click on the filter by product type dropdown select the option as the variable product, and click on the apply button.
  • Hover the cursor over the variable product name i.e. Hoodie and it will show the ID: 15 as shown below.

Set min and max quantities for the variable product

Imagine you run an online clothes store that sells clothes in various colors. You offer a variable product called “Hoodie” where customers can choose their favorite colors and also you want to set the minimum and maximum quantities for the variable product.

The below code snippets helps to modify the quantity field parameters for variable products.

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

function ts_min_max_qty_variable_products( $args, $product ) {
    $variation_product_id = array( 15 );
    if ( ! is_cart() && in_array( $product->get_id(), $variation_product_id ) ) {
        $args['min_value'] = 3;
        $args['max_value'] = 6;
    } elseif ( is_cart() && in_array( $product->get_parent_id(), $variation_product_id ) ) {
        $args['min_value'] = 3;
        $args['max_value'] = 6;
    }
    return $args;
}

Output

The output shows that the input field parameter is set to the minimum quantity of 3 and the maximum quantity of 6 for those specific variable product IDs specified in the code.

This code snippet connects to the quantity input arguments of WooCommerce and triggers a function called “ts_min_max_qty_variable_products” when the filter is applied. The function takes two parameters: $args and $product. 

An array of variation product IDs is created with only one product with ID 15. If the current page is not the cart page and the product being considered has an ID that matches any in the $variation_product_id array, the minimum quantity is set to 3 and the maximum quantity to 6. 

If the current page is the cart page and the parent product ID matches any in the $variation_product_id array, the minimum quantity is set to 3 and the maximum quantity to 6. 

Finally, the function returns the modified quantity input arguments that will be used by WooCommerce to display the quantity input field based on the specified conditions.

Creation of Minimum & Maximum Quantity fields:

Inventory tab of Product data meta box will be the best place to add our options. Using woocommerce_product_options_inventory_product_data hook we can add extra fields at the end of options available in Inventory tab. Below is the code snippet which will add “Minimum Quantity” and “Maximum Quantity” options in the Inventory tab.

function wc_qty_add_product_field() {

	echo '<div class="options_group">';
	woocommerce_wp_text_input( 
		array( 
			'id'          => '_wc_min_qty_product', 
			'label'       => __( 'Minimum Quantity', 'woocommerce-max-quantity' ), 
			'placeholder' => '',
			'desc_tip'    => 'true',
			'description' => __( 'Optional. Set a minimum quantity limit allowed per order. Enter a number, 1 or greater.', 'woocommerce-max-quantity' ) 
		)
	);
	echo '</div>';

	echo '<div class="options_group">';
	woocommerce_wp_text_input( 
		array( 
			'id'          => '_wc_max_qty_product', 
			'label'       => __( 'Maximum Quantity', 'woocommerce-max-quantity' ), 
			'placeholder' => '',
			'desc_tip'    => 'true',
			'description' => __( 'Optional. Set a maximum quantity limit allowed per order. Enter a number, 1 or greater.', 'woocommerce-max-quantity' ) 
		)
	);
	echo '</div>';	
}
add_action( 'woocommerce_product_options_inventory_product_data', 'wc_qty_add_product_field' );


Minimum and Maximum Quantity Options - set minimum and maximum quantities in WooCommerce
Minimum and Maximum Quantity Options

Next thing we need is saving the above options. Currently, they are only being shown on the Inventory section, but they won’t be saved if you enter values.

To save the values set to these options we will have to use woocommerce_process_product_meta action hook.

/*
* This function will save the value set to Minimum Quantity and Maximum Quantity options
* into _wc_min_qty_product and _wc_max_qty_product meta keys respectively
*/

function wc_qty_save_product_field( $post_id ) {
	$val_min = trim( get_post_meta( $post_id, '_wc_min_qty_product', true ) );
	$new_min = sanitize_text_field( $_POST['_wc_min_qty_product'] );

	$val_max = trim( get_post_meta( $post_id, '_wc_max_qty_product', true ) );
	$new_max = sanitize_text_field( $_POST['_wc_max_qty_product'] );
	
	if ( $val_min != $new_min ) {
		update_post_meta( $post_id, '_wc_min_qty_product', $new_min );
	}

	if ( $val_max != $new_max ) {
		update_post_meta( $post_id, '_wc_max_qty_product', $new_max );
	}
}
add_action( 'woocommerce_process_product_meta', 'wc_qty_save_product_field' );


When Publishing/Updating the product, the values set to “Minimum Quantity” and “Maximum Quantity” option will get saved in _wc_min_qty_product and _wc_max_qty_product meta keys of the post in the post_meta table.

Saved values in Minimum and Maximum Quantity - set minimum and maximum quantities in WooCommerce
Saved values in Minimum and Maximum Quantity

In the beginning of this post, we saw that we changed the minimum and maximum value for the quantity fields using the filter with some static values. In the below code we are fetching the values set to “Minimum Quantity” and “Maximum Quantity” and assigning it dynamically to arguments of quantity selector field.

/*
* Setting minimum and maximum for quantity input args. 
*/

function wc_qty_input_args( $args, $product ) {
	
	$product_id = $product->get_parent_id() ? $product->get_parent_id() : $product->get_id();
	
	$product_min = wc_get_product_min_limit( $product_id );
	$product_max = wc_get_product_max_limit( $product_id );	

	if ( ! empty( $product_min ) ) {
		// min is empty
		if ( false !== $product_min ) {
			$args['min_value'] = $product_min;
		}
	}

	if ( ! empty( $product_max ) ) {
		// max is empty
		if ( false !== $product_max ) {
			$args['max_value'] = $product_max;
		}
	}

	if ( $product->managing_stock() && ! $product->backorders_allowed() ) {
		$stock = $product->get_stock_quantity();

		$args['max_value'] = min( $stock, $args['max_value'] );	
	}

	return $args;
}
add_filter( 'woocommerce_quantity_input_args', 'wc_qty_input_args', 10, 2 );

function wc_get_product_max_limit( $product_id ) {
	$qty = get_post_meta( $product_id, '_wc_max_qty_product', true );
	if ( empty( $qty ) ) {
		$limit = false;
	} else {
		$limit = (int) $qty;
	}
	return $limit;
}

function wc_get_product_min_limit( $product_id ) {
	$qty = get_post_meta( $product_id, '_wc_min_qty_product', true );
	if ( empty( $qty ) ) {
		$limit = false;
	} else {
		$limit = (int) $qty;
	}
	return $limit;
}


Let’s understand what exactly is done in the above code snippet.

woocommerce_quantity_input_args is the filter which is used to alter the values being passed to create quantity field on the front end of the product page. Using this filter, in the callback wc_qty_input_args() function, we are setting the new values for min_value and max_value based on the values set in the “Minimum Quantity” and “Maximum Quantity” options.

You can now use the quantity limitations on the WooCommerce product page, which is only 1 part of the task.

Our second part is to have some validation on minimum and maximum quantity of the item when it is added to the cart and when it gets updated in the cart.

Validation on Add to Cart action

Let’s pause for a minute & think on why we need to validate on the add to cart action? For example, you have set the maximum quantity to 5 for Product A and you have added Product A for 5 quantity (max allowed quantity) in your basket. Now again you are adding Product A with 5 quantity and you are allowed to do this because there are no validations when the customer clicks on the “Add to Cart” button. That is why validation on the add to cart action is needed. Let’s see how we can do that.

WooCommerce has the woocommerce_add_to_cart_validation filter using which we can validate the add to cart action based on required conditions. As you can see in the below code snippet I have used the same filter. I

In the callback function wc_qty_add_to_cart_validation() I am checking that if the total quantity of the product in the cart is higher than the maximum quantity set for the product, then do not allow to add the product to the cart and display a WooCommerce error message.

/*
* Validating the quantity on add to cart action with the quantity of the same product available in the cart. 
*/
function wc_qty_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = '', $variations = '' ) {

	$product_min = wc_get_product_min_limit( $product_id );
	$product_max = wc_get_product_max_limit( $product_id );

	if ( ! empty( $product_min ) ) {
		// min is empty
		if ( false !== $product_min ) {
			$new_min = $product_min;
		} else {
			// neither max is set, so get out
			return $passed;
		}
	}

	if ( ! empty( $product_max ) ) {
		// min is empty
		if ( false !== $product_max ) {
			$new_max = $product_max;
		} else {
			// neither max is set, so get out
			return $passed;
		}
	}

	$already_in_cart 	= wc_qty_get_cart_qty( $product_id );
	$product 			= wc_get_product( $product_id );
	$product_title 		= $product->get_title();
	
	if ( !is_null( $new_max ) && !empty( $already_in_cart ) ) {
		
		if ( ( $already_in_cart + $quantity ) > $new_max ) {
			// oops. too much.
			$passed = false;			

			wc_add_notice( apply_filters( 'isa_wc_max_qty_error_message_already_had', sprintf( __( 'You can add a maximum of %1$s %2$s\'s to %3$s. You already have %4$s.', 'woocommerce-max-quantity' ), 
						$new_max,
						$product_title,
						'<a href="' . esc_url( wc_get_cart_url() ) . '">' . __( 'your cart', 'woocommerce-max-quantity' ) . '</a>',
						$already_in_cart ),
					$new_max,
					$already_in_cart ),
			'error' );

		}
	}

	return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'wc_qty_add_to_cart_validation', 1, 5 );

/*
* Get the total quantity of the product available in the cart.
*/ 
function wc_qty_get_cart_qty( $product_id ) {
	global $woocommerce;
	$running_qty = 0; // iniializing quantity to 0

	// search the cart for the product in and calculate quantity.
	foreach($woocommerce->cart->get_cart() as $other_cart_item_keys => $values ) {
		if ( $product_id == $values['product_id'] ) {				
			$running_qty += (int) $values['quantity'];
		}
	}

	return $running_qty;
}


Validation on the Add to Cart button click action - set minimum and maximum quantities in WooCommerce
Validation on the Add to Cart button click action

Validation on Updation of quantity in Cart page (woocommerce_update_cart_validation)

Again coming to the same question, why do we need to validate on Update Cart button action on the Cart page?

Because the customer can add Product A to the cart for 5 quantities and he is allowed to update the quantity higher than the value set to Minimum and Maximum Quantity options.

WooCommerce provides woocommerce_update_cart_validation filter to add the update cart action validations. Below is the code snippet which will do this validation.

/*
* Get the total quantity of the product available in the cart.
*/ 
function wc_qty_get_cart_qty( $product_id , $cart_item_key = '' ) {
	global $woocommerce;
	$running_qty = 0; // iniializing quantity to 0

	// search the cart for the product in and calculate quantity.
	foreach($woocommerce->cart->get_cart() as $other_cart_item_keys => $values ) {
		if ( $product_id == $values['product_id'] ) {

			if ( $cart_item_key == $other_cart_item_keys ) {
				continue;
			}

			$running_qty += (int) $values['quantity'];
		}
	}

	return $running_qty;
}

/*
* Validate product quantity when cart is UPDATED
*/

function wc_qty_update_cart_validation( $passed, $cart_item_key, $values, $quantity ) {
	$product_min = wc_get_product_min_limit( $values['product_id'] );
	$product_max = wc_get_product_max_limit( $values['product_id'] );

	if ( ! empty( $product_min ) ) {
		// min is empty
		if ( false !== $product_min ) {
			$new_min = $product_min;
		} else {
			// neither max is set, so get out
			return $passed;
		}
	}

	if ( ! empty( $product_max ) ) {
		// min is empty
		if ( false !== $product_max ) {
			$new_max = $product_max;
		} else {
			// neither max is set, so get out
			return $passed;
		}
	}

	$product = wc_get_product( $values['product_id'] );
	$already_in_cart = wc_qty_get_cart_qty( $values['product_id'], $cart_item_key );

	if ( isset( $new_max) && ( $already_in_cart + $quantity ) > $new_max ) {
		wc_add_notice( apply_filters( 'wc_qty_error_message', sprintf( __( 'You can add a maximum of %1$s %2$s\'s to %3$s.', 'woocommerce-max-quantity' ),
					$new_max,
					$product->get_name(),
					'<a href="' . esc_url( wc_get_cart_url() ) . '">' . __( 'your cart', 'woocommerce-max-quantity' ) . '</a>'),
				$new_max ),
		'error' );
		$passed = false;
	}

	if ( isset( $new_min) && ( $already_in_cart + $quantity )  < $new_min ) {
		wc_add_notice( apply_filters( 'wc_qty_error_message', sprintf( __( 'You should have minimum of %1$s %2$s\'s to %3$s.', 'woocommerce-max-quantity' ),
					$new_min,
					$product->get_name(),
					'<a href="' . esc_url( wc_get_cart_url() ) . '">' . __( 'your cart', 'woocommerce-max-quantity' ) . '</a>'),
				$new_min ),
		'error' );
		$passed = false;
	}

	return $passed;
}
add_filter( 'woocommerce_update_cart_validation', 'wc_qty_update_cart_validation', 1, 4 );


As you can see in the above code snippet I have used the woocommerce_update_cart_validation filter to perform some validations based on the minimum and maximum quantity set for the product and the total quantity of that particular product available in the cart.

After this, the user cannot update the cart with a quantity less than the value set to the “Minimum Quantity” option and greater than the value set to the “Maximum Quantity” option.

In this post, we learn how to set minimum and maximum allowable product quantities to be added to WooCommerce Cart using custom code. You can add some additional options or conditions based on your business requirements.

Free & Premium WooCommerce plugins to set minimum & maximum quantity for products

There are paid plugins available that come with many other options to play with minimum and maximum allowed quantity and its rules. You can check the Minimum and Maximum Quantity for WooCommerce plugin which allows setting the Min/Max Quantity rule at the product level as well as at cart level. And it also allows setting minimum and maximum cart amount rules.

Below is the list of the free plugins available on WordPress.org which allows to set minimum and maximum allowable product quantities to be added in WooCommerce Cart.

1. Min and Max Quantity for WooCommerce
2. WooCommerce Minimum and Maximum Quantity
3. WooCommerce Max Quantity

Conclusion

Limiting the minimum & a maximum quantity of product can be achieved by using the filters provided by WooCommerce. Also, we have seen in this post that using some custom code snippets (including the filter available in WooCommerce) you can create proper interface and validations for allowing minimum and maximum quantity for the product. Or you can install already available plugins on your WordPress Repository and achieve the same.

In our Booking & Appointment plugin for WooCommerce, we added a feature recently where we are limiting the maximum allowed quantity for a product to be booked based on the Maximum booking set in our plugin. That’s where I got the idea to write this as a post.

Maximum quantity based on Maximum Bookings - set minimum and maximum quantities in WooCommerce
Maximum quantity based on Maximum Bookings

I hope this post helps you to learn how things in the WooCommerce can be easily customizable. If you have any questions then feel free to comment it.

Browse more in: WooCommerce, WooCommerce How Tos, WooCommerce Tutorials

Share It:

99 thoughts on “How to set minimum and maximum allowable product quantities to be added in WooCommerce Cart

  1. Hi. Thanks for the code. Got the add to cart limitation working great. But can not make the update quantity cart working. My cart has ajax update on quantity update, so no update cart button. Because of this filter called woccommerce_update_cart_validation does not take any action. It’s not even getting called. What filter/action should I use instead?

    1. Hi Pete,
      Thank you for your feedback. Since your cart updates quantities using AJAX and there’s no “Update Cart” button, the woocommerce_update_cart_validation filter won’t be triggered. Instead, you can try using the ‘woocommerce_after_cart_item_quantity_update’ action hook, which should work for both regular and AJAX-based quantity changes in the cart. Kindly let us know if this resolves the issue.

  2. Hi.

    Thanks for this post. It ve been very usefull.

    This code work fine on Product page but it doesnt work on cartpage. Which changes it would need to work on the cart page?

    Bye!!

    1. Hi Isaac,
      There are many code snippets provided in the post with various functionalities. Regarding your query, could you please specify which specific code snippet you have tried from the post?

      1. This is the code i use. Thanks for your help
        function wc_qty_add_product_field() {
           echo ‘<div class=”options_group”>’;
           woocommerce_wp_text_input(
             array(
               ‘id’      => ‘_wc_mind_qty_product’,
               ‘label’    => __‘Cantidad Minima Detal’‘woocommerce-max-quantity’ ),
               ‘placeholder’ => ‘Ejem 1. Dejelo vacío si no desea configurar un minimo’,
               ‘desc_tip’   => ‘true’,
               ‘description’ => __‘Opcional. Configurar la cantidad minima permitida para el cliente detal.’‘woocommerce-max-quantity’ ),
               ‘type’        => ‘number’,
               ‘custom_attributes’ => array(
                 ‘step’ => ‘any’,
                 ‘min’  => ‘0’,
              )
        )
          );
           echo ‘</div>’;
           echo ‘<div class=”options_group”>’;
           woocommerce_wp_text_input(
             array(
               ‘id’      => ‘_wc_maxd_qty_product’,
               ‘label’    => __‘Cantidad Maxima Detal’‘woocommerce-max-quantity’ ),
               ‘placeholder’ => ‘Ejem 24. Dejelo vacío si no desea configurar un máximo’,
               ‘desc_tip’   => ‘true’,
               ‘description’ => __‘Opcional. Configurar la cantidad máxima permitida para el cliente detal’‘woocommerce-max-quantity’ ),
               ‘type’        => ‘number’,
               ‘custom_attributes’ => array(
                 ‘step’ => ‘any’,
                 ‘min’  => ‘0’,
              )
        )
          );
           echo ‘</div>’;  
           echo ‘<div class=”options_group”>’;
           woocommerce_wp_text_input(
             array(
               ‘id’      => ‘_wc_incd_qty_product’,
               ‘label’    => __‘Incremento para Detal’‘woocommerce-max-quantity’ ),
               ‘placeholder’ => ‘Ejem 3. Dejelo vacío si no desea configurar el incremento’,
               ‘desc_tip’   => ‘true’,
               ‘description’ => __‘Opcional. Configure la cantidad de incremento para Detal.’‘woocommerce-max-quantity’ ),
               ‘type’        => ‘number’,
               ‘custom_attributes’ => array(
                 ‘step’ => ‘any’,
                 ‘min’  => ‘0’,
              )
        )
          );
           echo ‘</div>’;

        }
        add_action‘woocommerce_product_options_inventory_product_data’‘wc_qty_add_product_field’ );

        /***************************************************************************/
        /***************************************************************************/
        /***************************************************************************/
        /***************************************************************************/

        /*
        * Esta funcion permite guardar los campos incremento, minimo y maximos en la ficha de productos
        * into _wc_min_qty_product and _wc_max_qty_product
        */
        function wc_qty_save_product_field$post_id ) {

           $val_min = trimget_post_meta$post_id‘_wc_mind_qty_product’true ) );
           $new_min = sanitize_text_field$_POST[‘_wc_mind_qty_product’] );
           $val_max = trimget_post_meta$post_id‘_wc_maxd_qty_product’true ) );
           $new_max = sanitize_text_field$_POST[‘_wc_maxd_qty_product’] );
           $val_inc = trimget_post_meta$post_id‘_wc_incd_qty_product’true ) );
           $new_inc = sanitize_text_field$_POST[‘_wc_incd_qty_product’] );
          
           if ( $val_min != $new_min ) {
             update_post_meta$post_id‘_wc_mind_qty_product’$new_min );
          }
           if ( $val_max != $new_max ) {
             update_post_meta$post_id‘_wc_maxd_qty_product’$new_max );
          }
           if ( $val_inc != $new_inc ) {
             update_post_meta$post_id‘_wc_incd_qty_product’$new_inc );
          }
        }
        add_action‘woocommerce_process_product_meta’‘wc_qty_save_product_field’ );

        /***************************************************************************/
        /***************************************************************************/
        /***************************************************************************/
        /***************************************************************************/

        /*
        * Validando la cantidad que se agrega al carrito
        */
        function wc_qty_add_to_cart_validation$passed$product_id$quantity$variation_id = $variations =  ) {
           $product_min = wc_get_product_min_limit$product_id );
           $product_max = wc_get_product_max_limit$product_id );
           $product_inc = wc_get_product_inc_limit$product_id );
           $args[‘step’] = $product_inc;

           if ( ! empty$product_min ) ) {
             // min is empty
             if ( false !== $product_min ) {
               $new_min = $product_min;
               $args[‘min_value’] = $product_min;
            } else {
               // neither max is set, so get out
               return $passed;
            }
          }
           if ( ! empty$product_max ) ) {
             // min is empty
             if ( false !== $product_max ) {
               $new_max = $product_max;
               $args[‘max_value’] = $product_max;
            } else {
               // neither max is set, so get out
               return $passed;
            }
          }
           $already_in_cart   = wc_qty_get_cart_qty$product_id );
           $product       = wc_get_product$product_id );
           $product_title     = $product->get_title();
          
           if ( !is_null$new_max ) && !empty$already_in_cart ) ) {
            
             if ( ( $already_in_cart + $quantity ) > $new_max ) {
               // oops. too much.
               $passed = false;      
               wc_add_noticeapply_filters‘isa_wc_max_qty_error_message_already_had’sprintf__‘Puede agregar un maximo de %1$s %2$s\’s a %3$s. Actualmente tiene %4$s.’‘woocommerce-max-quantity’ ),
                     $new_max,
                     $product_title,
                     ‘<a href=”‘ . esc_urlwc_get_cart_url() ) . ‘”>’ . __‘su carrito’‘woocommerce-max-quantity’ ) . ‘</a>’,
                     $already_in_cart ),
                   $new_max,
                   $already_in_cart ),
               ‘error’ );
            }
          }
           return $passed;
        }
        add_filter‘woocommerce_add_to_cart_validation’‘wc_qty_add_to_cart_validation’15 );
        /*
        * Get the total quantity of the product available in the cart.
        */
        function wc_qty_get_cart_qty$product_id ) {
           global $woocommerce;
           $running_qty = 0// iniializing quantity to 0
           // search the cart for the product in and calculate quantity.
           foreach($woocommerce->cart->get_cart() as $other_cart_item_keys => $values ) {
             if ( $product_id == $values[‘product_id’] ) {        
               $running_qty += (int$values[‘quantity’];
            }
          }
           return $running_qty;
        }

        /***************************************************************************/
        /***************************************************************************/
        /***************************************************************************/
        /***************************************************************************/

        /*
        * Se configura la entrada de valores segun el incremento, minimos y maximos cofigurados en el producto
        */
        function wc_qty_input_args$args$product ) {
          
           $product_id = $product->get_parent_id() ? $product->get_parent_id() : $product->get_id();
          
           $product_min = wc_get_product_min_limit$product_id );
           $product_max = wc_get_product_max_limit$product_id );
           $product_inc = wc_get_product_inc_limit$product_id );
           $args[‘step’] = $product_inc;

           if ( ! empty$product_min ) ) {
             // min is empty
             if ( false !== $product_min ) {
               $args[‘min_value’] = $product_min;
            }
          }
           if ( ! empty$product_max ) ) {
             // max is empty
             if ( false !== $product_max ) {
               $args[‘max_value’] = $product_max;
            }
          }
           if ( $product->managing_stock() && ! $product->backorders_allowed() ) {
             $stock = $product->get_stock_quantity();
             $args[‘max_value’] = min$stock$args[‘max_value’] );  
          }
           return $args;
        }
        add_filter‘woocommerce_quantity_input_args’‘wc_qty_input_args’102 );
        add_filter‘woocommerce_cart_item_quantity’‘wc_qty_input_args’102 );

        function wc_get_product_max_limit$product_id ) {
           $qty = get_post_meta$product_id‘_wc_maxd_qty_product’true );
           if ( empty$qty ) ) {
             $limit = false;
          } else {
             $limit = (int$qty;
          }
           return $limit;
        }
        function wc_get_product_min_limit$product_id ) {
           $qty = get_post_meta$product_id‘_wc_mind_qty_product’true );
           if ( empty$qty ) ) {
             $limit = false;
          } else {
             $limit = (int$qty;
          }
           return $limit;
        }

        function wc_get_product_inc_limit$product_id ) {
          
           $limit = 1;
           $qty = get_post_meta$product_id‘_wc_incd_qty_product’true );
           if ( empty$qty ) ) {
             $limit = 1;
          } else {
             $limit = (int$qty;
          }
           return $limit;
        }

        1. Hi Isaac,
          The code that you provided is missing the part that handles validation on the cart page. After reviewing the code shared in our blog post, we identified some function name conflicts that were preventing the validation from working properly. We’ve addressed these conflicts and updated the code in the blog post. You can access the full code here from the GitHub repository:https://github.com/tychewriters/woocommerce-min-max-quantity-manager

  3. This works perfectly. Most free plugins don’t allow you to set a limit per product, which is exactly what most. people need. Thanks a lot for the code and the insightful explanation of it.

    My only suggestion would be to include all the code at the end. Now I had to copy and paste it from 4 fields. But this is minor.

    1. Hi Vlad, 

      The provided code snippet does not work for variable products. It only works for simple product types. If you’re looking to set the min/max for variable products. Here is the code snippet for setting the min/max for the product quantities.

      // Set min and max quantity for  product variation

      add_filter( ‘woocommerce_quantity_input_args’, ‘wc_min_max_qty_variable_products’, 10, 2 );
      function wc_min_max_qty_variable_products( $args, $product ) {
          $sample_product_id = array( 15 );
          if ( ! is_cart() && in_array( $product->get_id(), $sample_product_id ) ) {
              $args[‘min_value’] = 3;
              $args[‘max_value’] = 6;
          } elseif ( is_cart() && in_array( $product->get_parent_id(), $sample_product_id ) ) {
              $args[‘min_value’] = 1;
              $args[‘step’] = 1;
          }
          return $args;
      }

      Here is the output for your reference – https://prnt.sc/lAnBZLhGngpo

        1. Hi Joe,
          We have updated the post based on your request to implement the steps for setting the min/max quantity for variable products. Please refer to the heading “Where to Add Custom Code in WooCommerce?” and “Set min and max quantities for the variable product”

  4. hi. I put all the codes that you put in the function file of my site. When I put the last piece of code, the site encountered a problem and was no longer available.

    Validation on Updation of quantity in Cart page
    Please guide me how to use these codes so that my site works properly

    1. Hi mahsa,

      I understand that your site went down after adding the code snippet for product quantity validation in the cart. Here’s how you can troubleshoot the issue:

      • Double-check the code you copied and ensure there are no typos or syntax errors.
      • You might have another plugin installed that conflicts with the custom code for product quantity validation.

      By following these steps you can able to identify the cause of the problem of your site.

  5. Hi,

    When adding the last code snippet to validate upon updating the car quantity I got the following error:

    Cannot redeclare function wc_qty_get_cart_qty.

    Any ideas about what’s going on there and how to fix it?

    1. Hi David,

      The error you’re experiencing (“Cannot redeclare function wc_qty_get_cart_qty”) indicates that the function is already defined somewhere else in your code or in another plugin. You can rename the function in our code at 2 places & that should fix it. Change it on line 29 and on line 58. You can rename the function name as: ts_wc_qty_get_cart_qty .

  6. hi,
    for me it shouldn’t matter how many products are in the shopping cart, it just can’t be 4. What would the snippet look like then?

  7. Hi, I wanted to add a shortcode to the code so I can display the minimum order value quantity on the product shop page. I was not sure where to place the add_shortcode( ‘shortcode_name’ , ‘callback_function’ ).
    I was going to place it in this function “function wc_get_product_min_limit()”.

  8. Hi,

    thx for the above tutorial, it’s very useful,

    but can i do something like this for the minimum & maximum amount (cart & check out)

    for different currencies?
    as all codes i found or plugin works for the default currency only

    THx in advance

  9. Hello Kartik – Thank you for this great code snippet. It works very well except when the snippet is active, the user can no longer update the item quantities on the cart page. When they change the number and press “Update cart” the page refreshes and the item quantities reset. Do you know why this may be? Here is the code I am using.

    function wc_qty_add_product_field() {
    
    
    	echo '<div class="options_group">';
    	woocommerce_wp_text_input( 
    		array( 
    			'id'          => '_wc_min_qty_product', 
    			'label'       => __( 'Minimum Quantity', 'woocommerce-max-quantity' ), 
    			'placeholder' => '',
    			'desc_tip'    => 'true',
    			'description' => __( 'Optional. Set a minimum quantity limit allowed per order. Enter a number, 1 or greater.', 'woocommerce-max-quantity' ) 
    		)
    	);
    	echo '</div>';
    
    
    	echo '<div class="options_group">';
    	woocommerce_wp_text_input( 
    		array( 
    			'id'          => '_wc_max_qty_product', 
    			'label'       => __( 'Maximum Quantity', 'woocommerce-max-quantity' ), 
    			'placeholder' => '',
    			'desc_tip'    => 'true',
    			'description' => __( 'Optional. Set a maximum quantity limit allowed per order. Enter a number, 1 or greater.', 'woocommerce-max-quantity' ) 
    		)
    	);
    	echo '</div>';	
    }
    add_action( 'woocommerce_product_options_inventory_product_data', 'wc_qty_add_product_field' );
    
    
    function wc_qty_save_product_field( $post_id ) {
    	$val_min = trim( get_post_meta( $post_id, '_wc_min_qty_product', true ) );
    	$new_min = sanitize_text_field( $_POST['_wc_min_qty_product'] );
    
    
    	$val_max = trim( get_post_meta( $post_id, '_wc_max_qty_product', true ) );
    	$new_max = sanitize_text_field( $_POST['_wc_max_qty_product'] );
    	
    	if ( $val_min != $new_min ) {
    		update_post_meta( $post_id, '_wc_min_qty_product', $new_min );
    	}
    
    
    	if ( $val_max != $new_max ) {
    		update_post_meta( $post_id, '_wc_max_qty_product', $new_max );
    	}
    }
    add_action( 'woocommerce_process_product_meta', 'wc_qty_save_product_field' );
    
    
    function wc_qty_input_args( $args, $product ) {
    	
    	$product_id = $product->get_parent_id() ? $product->get_parent_id() : $product->get_id();
    	
    	$product_min = wc_get_product_min_limit( $product_id );
    	$product_max = wc_get_product_max_limit( $product_id );	
    
    
    	if ( ! empty( $product_min ) ) {
    		// min is empty
    		if ( false !== $product_min ) {
    			$args['min_value'] = $product_min;
    		}
    	}
    
    
    	if ( ! empty( $product_max ) ) {
    		// max is empty
    		if ( false !== $product_max ) {
    			$args['max_value'] = $product_max;
    		}
    	}
    
    
    	if ( $product->managing_stock() && ! $product->backorders_allowed() ) {
    		$stock = $product->get_stock_quantity();
    
    
    		$args['max_value'] = min( $stock, $args['max_value'] );	
    	}
    
    
    	return $args;
    }
    add_filter( 'woocommerce_quantity_input_args', 'wc_qty_input_args', 10, 2 );
    
    
    function wc_get_product_max_limit( $product_id ) {
    	$qty = get_post_meta( $product_id, '_wc_max_qty_product', true );
    	if ( empty( $qty ) ) {
    		$limit = false;
    	} else {
    		$limit = (int) $qty;
    	}
    	return $limit;
    }
    
    
    function wc_get_product_min_limit( $product_id ) {
    	$qty = get_post_meta( $product_id, '_wc_min_qty_product', true );
    	if ( empty( $qty ) ) {
    		$limit = false;
    	} else {
    		$limit = (int) $qty;
    	}
    	return $limit;
    }
    
    
    function wc_qty_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = '', $variations = '' ) {
    
    
    	$product_min = wc_get_product_min_limit( $product_id );
    	$product_max = wc_get_product_max_limit( $product_id );
    
    
    	if ( ! empty( $product_min ) ) {
    		// min is empty
    		if ( false !== $product_min ) {
    			$new_min = $product_min;
    		} else {
    			// neither max is set, so get out
    			return $passed;
    		}
    	}
    
    
    	if ( ! empty( $product_max ) ) {
    		// min is empty
    		if ( false !== $product_max ) {
    			$new_max = $product_max;
    		} else {
    			// neither max is set, so get out
    			return $passed;
    		}
    	}
    
    
    	$already_in_cart 	= wc_qty_get_cart_qty( $product_id );
    	$product 			= wc_get_product( $product_id );
    	$product_title 		= $product->get_title();
    	
    	if ( !is_null( $new_max ) && !empty( $already_in_cart ) ) {
    		
    		if ( ( $already_in_cart + $quantity ) > $new_max ) {
    			// oops. too much.
    			$passed = false;			
    
    
    			wc_add_notice( apply_filters( 'isa_wc_max_qty_error_message_already_had', sprintf( __( 'There is a limit of %1$s %2$s\'s per order. You currently have %4$s in %3$s.', 'woocommerce-max-quantity' ), 
    						$new_max,
    						$product_title,
    						'<a href="' . esc_url( wc_get_cart_url() ) . '">' . __( 'your cart', 'woocommerce-max-quantity' ) . '</a>',
    						$already_in_cart ),
    					$new_max,
    					$already_in_cart ),
    			'error' );
    
    
    		}
    	}
    
    
    	return $passed;
    }
    add_filter( 'woocommerce_add_to_cart_validation', 'wc_qty_add_to_cart_validation', 1, 5 );
    
    
    /*
    * Get the total quantity of the product available in the cart.
    */ 
    function wc_qty_get_cart_qty( $product_id , $cart_item_key = '' ) {
    	global $woocommerce;
    	$running_qty = 0; // iniializing quantity to 0
    
    
    	// search the cart for the product in and calculate quantity.
    	foreach($woocommerce->cart->get_cart() as $other_cart_item_keys => $values ) {
    		if ( $product_id == $values['product_id'] ) {
    
    
    			if ( $cart_item_key == $other_cart_item_keys ) {
    				continue;
    			}
    
    
    			$running_qty += (int) $values['quantity'];
    		}
    	}
    
    
    	return $running_qty;
    }
    
    
    function wc_qty_update_cart_validation( $passed, $cart_item_key, $values, $quantity ) {
    	$product_min = wc_get_product_min_limit( $values['product_id'] );
    	$product_max = wc_get_product_max_limit( $values['product_id'] );
    
    
    	if ( ! empty( $product_min ) ) {
    		// min is empty
    		if ( false !== $product_min ) {
    			$new_min = $product_min;
    		} else {
    			// neither max is set, so get out
    			return $passed;
    		}
    	}
    
    
    	if ( ! empty( $product_max ) ) {
    		// min is empty
    		if ( false !== $product_max ) {
    			$new_max = $product_max;
    		} else {
    			// neither max is set, so get out
    			return $passed;
    		}
    	}
    
    
    	$product = wc_get_product( $values['product_id'] );
    	$already_in_cart = wc_qty_get_cart_qty( $values['product_id'], $cart_item_key );
    
    
    	if ( ( $already_in_cart + $quantity ) > $new_max ) {
    		wc_add_notice( apply_filters( 'wc_qty_error_message', sprintf( __( 'There is a limit of %1$s %2$s\'s per order. You currently have %4$s in %3$s.', 'woocommerce-max-quantity' ),
    					$new_max,
    					$product->get_name(),
    					'<a href="' . esc_url( wc_get_cart_url() ) . '">' . __( 'your cart', 'woocommerce-max-quantity' ) . '</a>'),
    				$new_max ),
    		'error' );
    		$passed = false;
    	}
    
    
    	if ( ( $already_in_cart + $quantity )  < $new_min ) {
    		wc_add_notice( apply_filters( 'wc_qty_error_message', sprintf( __( 'You should have minimum of %1$s %2$s\'s to %3$s.', 'woocommerce-max-quantity' ),
    					$new_min,
    					$product->get_name(),
    					'<a href="' . esc_url( wc_get_cart_url() ) . '">' . __( 'your cart', 'woocommerce-max-quantity' ) . '</a>'),
    				$new_min ),
    		'error' );
    		$passed = false;
    	}
    
    
    	return $passed;
    }
    add_filter( 'woocommerce_update_cart_validation', 'wc_qty_update_cart_validation', 1, 4 );
    
    
    
    
    add_action( 'woocommerce_product_after_variable_attributes', 'wc_variation_settings_fields', 10, 3 );
    add_action( 'woocommerce_save_product_variation', 'wc_save_variation_settings_fields', 10, 2 );
    add_filter( "woocommerce_available_variation", "woocommerce_available_variation_callback", 10, 3 );
    
    
    /**
    * Adding Min and Max field in variations 
    *
    * @since 1.0
    */
    function wc_variation_settings_fields( $loop, $variation_data, $variation ) {
      wp_nonce_field('wc_minmax', 'wc_variation_edit');
    
    
      woocommerce_wp_text_input( 
          array( 
              'id'                => 'wc_min_quantity_var[' . $variation->ID . ']', 
              'label'             => __( 'Minimum Quantity Var', 'min-max' ),
              'value'             => get_post_meta( $variation->ID, '_wc_min_qty_product', true ),
              'custom_attributes' => array('min' => '1'),
              'wrapper_class'     => 'wc_min_max_clear'
          )
      );
    
    
      woocommerce_wp_text_input( 
          array( 
              'id'                => 'wc_max_quantity_var[' . $variation->ID . ']', 
              'label'             => __( 'Maximum Quantity Var', 'min-max' ),
              'value'             => get_post_meta( $variation->ID, '_wc_max_qty_product', true ),
              'custom_attributes' => array('min' => '1')
          )
      );
    }
    
    
    /**
     * Saving Min and Max value for variations
     *
     * @since 1.0
     */
    function wc_save_variation_settings_fields( $post_id ) {
        if ( empty($_REQUEST['wc_variation_edit']) || ! wp_verify_nonce( $_REQUEST['wc_variation_edit'], 'wc_minmax') ) {
            return;
        }
        if ( isset( $_POST['wc_min_quantity_var'][ $post_id ] ) ) {
            update_post_meta( $post_id, '_wc_min_qty_product', $_POST['wc_min_quantity_var'][ $post_id ] );
        }
        if ( isset( $_POST['wc_max_quantity_var'][ $post_id ] ) ) {
            update_post_meta( $post_id, '_wc_max_qty_product', $_POST['wc_max_quantity_var'][ $post_id ] );
        }
    }
    
    
    /**
     * Applying Min and Max value on front end.
     *
     * @since 1.0
     */
    function woocommerce_available_variation_callback( $variation_array, $this_something, $variation ) {
    
    
      $parent_id    = $variation->get_parent_id();
      $variation_id = $variation->get_id();
    
    
      $pro_min = get_post_meta( $parent_id, "_wc_min_qty_product", true );
      $pro_max = get_post_meta( $parent_id, "_wc_max_qty_product", true );
    
    
      if ( $pro_min == "" ){ // if parent min is not set then check for variation min
        $min = wc_get_product_min_limit( $variation_id );
        if ( $min != "" ){
          $variation_array['min_qty'] = $min;
        }
      }else{
        $variation_array['min_qty'] = $pro_min;
      }
    
    
      if ( $pro_max == "" ){ // if parent max is not set then check for variation max
        $max = wc_get_product_max_limit( $variation_id );
        if ( $max != "" ){
          $variation_array['max_qty'] = $max;
        }	
      } else {
        $variation_array['max_qty'] = $pro_max;
      }
    
    
      return $variation_array;
    }
    
  10. Hello, I would like to have a minimum qty of 0.5 for a specific product. where should paste this code? your code is working fine when setting minimum of 1 is working but when I set 0.5 it doesn’t work unless I remove the intval and replace it with floatval. my problem is I don’t know where exactly to put this code below. I don’t want to put it outside the function because it will affect all the products

    remove_filter(‘woocommerce_stock_amount’‘intval’);
    add_filter(‘woocommerce_stock_amount’‘floatval’);

  11. Hi, I am using your code snippet to set min and max quantities on a woo product. Is there a way to set the increments and also can the quantity min max be product category or tag specific?

  12. Hi,

    Woocomerce Shipping: Free shipping on the minimum order.

    The code in this article does not work with the minimum order quantity rule.
    On our swag products, we wanted to offer free shipping, and that is when we found the error.

    Click on the link: https://diversityavatarstickers.com/product/das-swag-shirts-xs/
    Add the minimum order quantity to the cart and it still calculates the flat shipping rule.

    PHP FILE: https://drive.google.com/file/d/1Qf3yhiF7ShfSMZlBOSj4RS7OtXbl4bCP/view?usp=sharing

  13. Hello,
    When you add the product directly to the cart from the store page and then go to the payment page, the purchase can be made.

    1. You mean without complying to the set minimum quantity? If yes, I experience the same issue. Did you find a solution for it?

  14. Hi Kartik,
    Is it possible additionally to restrict the min-max based on the $product_id? In my webshop there are 2 physical item and the rest virtual. I can apply your code and it is working but it also counting the virtual products. Eg. my max limit 32, if I have 30 books and 2 virtual products(ebook) in the cart it does not allow to add more than 30 physical books. But I’d like to allow to buy as much virtual product the customer want.

    Thanks.
    Joe

  15. If someone copy and paste all the code (creation of fields, add to cart validation and update cart validation) the function “function wc_qty_get_cart_qty” is written twice (on “Validation on Add to Cart action” and on “Validation on Updation of quantity in Cart page”) and I got an error. I deleted the first one and it worked. is it right? thanks

  16. I caught a flaw in your code.
    The first try the first time adding 999 amount to cart, it will not work.
    For example, I set limit maximum to 10, but on the first try the first time add-to-cart I put 999 and it goes through without warning without error.
    So your code does not catch the limit on first try. How do you fix this?

  17. Hi, good, but there is a flaw/mistake. For example I set the maximum to 15. And then I open the shop page for the first time and add 55 to cart. It ALLOWS it !!
    On the first try, the first time you try to add to cart you can set ANY AMOUNT and it will not give error/warning of maximum.
    So your code only works when someone try to add again or someone try to change amount, only then the limit of maximum works.
    Do you know how to fix this? Catch the wrong amount the first time add-to-cart ?

  18. Great tips. Thank you.

    Just a question.

    For several products, I must, for example, impose to order by quantity of 6 (6 bottle, 12 bottles, …)

    Do you have this tips ?

    Thank you

    1. Hi Mike,

      Can you please let me know that you want to set rules on the cart so that customers are forced to order the products with a total of 6 OR 12 quantity?
      E.g
      1. Cart contains Product A with 4 quantity and Product B with 2 quantity: Allows to place the order.
      2. Cart contains Product A with 5 quantity and Product B with 3 quantity: Do not allow to place the order.
      3. Cart contains Product A with 8 quantity and Product B with 4 quantity: Allow to place the order.

      If I misunderstood your requirements then please elaborate with some example so that I can understand correctly and get back to you with the optimal answer.

  19. ciao , i insert your code with some modification, but input field for qty don’t stop on min value (on max it’s run) why??? what i ca do??
    Thanks

    1. Hi,

      Can you share the code snippet so that I can test it once at my end and help you to resolve the issue?
      You can drop me an email on the below email address.
      Email : kartik at tychesoftwares dot com

  20. How To Add Message for Minimum product? When some one want to buy a product, he get message that this item must by with minimum order?

    1. Do you want to display a ‘minimum quantity for product message’ above the quantity selector so that customers will choose the appropriate quantity for the product? If that is the case, then you can use ‘woocommerce_before_add_to_cart_button’ hook and in the callback, you can fetch the data and display the message.

      If you want us to implement that code snippet for you then it will be chargeable and you can drop an email on the below email address.
      Email Address: kartik at tychesoftwares dot com

  21. First, thank you so much for creating this example.

    I received the following errors.

    Notice: Undefined variable: new_max in /home/mySever/myDomain.com/wp-content/themes/das-theme/inc/min-and-max-product-quantities.php on line 148
    [cmnq_min_max_quantity.php]
    LINE 148: if ( !is_null( $new_max ) && !empty( $already_in_cart ) )…

    Warning: Cannot modify header information – headers already sent by (output started at /home/mySever/myDomain.com/wp-content/themes/das-theme/inc/min-and-max-product-quantities.php:148) in /home/mySever/myDomain.com/wp-includes/pluggable.php on line 1265

    Warning: Cannot modify header information – headers already sent by (output started at /home/mySever/myDomain.com/wp-content/themes/das-theme/inc/min-and-max-product-quantities.php:148) in /home/mySever/myDomain.com/wp-includes/pluggable.php on line 1268

    I did not place a max number only a minimum number.

    Tarzine

    1. I am also getting an error when I don’t use a max quantity.

      Undefined variable: new_max

      ( !is_null( $new_max ) && !empty( $already_in_cart ) ) {

  22. thanks for the good article!

    I have been using the WooCommerce Min/Max plugin. Now I am trying to skip the Cart and send users directly to Checkout, and I allow users to change product Qty in checkout using your plugin – thanks for that!!!

    but if you set a Global (Woocommerce->Settings->General->Min/Max Quantity) Min order qty to 2 (for example), validation works well in the Cart, but it does not work in the Checkout. So a user can nicely go in the Checkout below 2 (which is 1).

    Of course, I can set Min Order Qty to 2 for each product, but this is ugly – I want user to be able to buy 2 products including one Product A + one Product B, not 2 of each.

    Do you have any ideas how I can set validation on the Checkout page? Thank you!!!

    1. Hi Oleg,

      Do you mean to say that the validation fails when redirecting to the checkout page upon add to cart? Please let me know.
      Try using ‘woocommerce_before_checkout_process’ action hook to validate based on your requirement and let me know if that helps or not.

      1. Kartik, thanks for your reply!

        I mean that the WooCommerce Min/Max validation of Global Minimum order Qty (for examplle 2) only works on the Cart page, and does not work on the Checkout page.

        So if a user sets the Order Qty =2 on the Cart page, and goes to the Cehcout page, where I use your plugin to change product order Qty, the user can change Order Qty to 1 and no warning is displayed.

        However, if I use the WooCommerce Min/Max and set a product-specific Minimum qty to 2, on the Checkout page the user cannot set Qty for this product to 1 – if he clicks (-) nothing happens.

        So what I am struggling with, is how to design a rule to use together with your plugin, that on the Checkout page, the total Qty of products ordered cannot go below the Global Minimum Order Qty :))))

        If you have any ideas please tell me.

    1. Hi Paul,

      Thank you for sharing the screenshot.

      I have created a solution for it based on the solution provided on the below link.
      Link: https://stackoverflow.com/questions/5272433/html5-form-required-attribute-set-custom-validation-message

      What you can do is, override the template file of the quantity field as follow.
      – Create (or replace if existing) the wp-content/themes/{your-theme}/woocommerce/global/quantity-input.php file.
      – The code contains in the below link can be used inside that template.
      https://gist.github.com/kartikparmar/e9efde689f5e498e0e6686196d67760a

      Please let me know if this will help or not.

      1. Thank you Kartik! This is almost exactly what I need. It works great if you hit that very large number, but then if you erase the number and enter a low number like 1, the message still shows up, unless you refresh the page and try again. Is it possible to adjust the code to allow a lower number to be entered without refreshing the page? If not, this isn’t a big deal.

        Also you mentioned that when WooCommerce does an update that this will probably be overwritten? Would it be as simple as re-adding the php to re-enable it?

        1. Hi Paul,

          I am glad to know that it worked for you. 🙂

          Frankly speaking I have not tested that case and I am not sure if it is possible solve that or not. I will try to look into it once I will get some free time.

          Do not worry about WooCommerce update as your file is inside your theme. But the theme update will cause the problem here as you will have to again add the file after the theme update. If you have created child theme and placed this file inside it then you are safe. 😉 Sorry I forgot to mention about child theme in my previous response.

          :Kartik

    1. Hi Khazra,

      I am glad to know that the information shared in this post was useful to you. 🙂

      : Kartik

  23. This works really well! However, I have over 700 products which all have minimum order quantities. Is there a way to bulk upload the minimum order quantities from a spreadsheet/CSV file so that I don’t have to do them one by one? I’ve tried using WP All Import, but the min/max fields don’t show up there.

    Thanks for any help or suggestions.

    1. Hey Mark,

      I am glad to know that the information shared in the post helped you to achieve your requirement. 🙂

      I am sorry to say that currently there is no way to bulk upload the minimum order values to all your 700 products. But maybe by custom script, or database query or making this compatible with WP All Import plugin you can achieve it.

  24. Hi
    Im a Newbie in Woocommerce, so….
    Do i put all the code (6 times) above in function.php at my child-theme

    Best Regards
    APPweb
    Denmark

    1. Hi,

      The very first code snippet is just to demonstrate how to hardcode the custom min/max quantity. So you can skip the first one and include rest of the snippets in your functions.php of your currently active theme.

      1. Hi, i finally got it to work BUT how can i get i to do i in steps (interval)…?
        one product i sale in 3,6,9,12,15…ect.
        another i sale in 6,12,18,24…ect.

        1. Hi,

          You can use ‘woocommerce_quantity_input_args’ filter and modify the attributes of quantity fields as per your business requirements.

  25. Hi Kartik,

    Thank you for writing this! I have added the code and I am unable to add more than the max number I have set (96) as expected. When I try to type in a greater number an error message appears with the message “Value must be less than or equal to 96”. The problem is when I add 96 from the store page and then an additional 1 or any number product, it doesn’t add to the cart but the error message doesn’t display. I am running WP 5.3 with the DIVI theme and Woocommerce 3.5.1.

    Please help!

    Thanks,
    Nick

    1. Hi Nick,

      I tried to replicate the same but at my end, it’s working fine. I have v3.13.1 of DIVI theme so the only difference would be the theme version. But I am not sure if that will cause an issue. Can you please switch to the Storefront theme or WordPress default theme and see if the same issue still persists?

  26. Hi there,

    Great article i realy like how you share your knowladge!!

    I am using Woocommerce Minimum and Maximum Quantity by Ashok G a free plugin that allows you to set min max quantity.
    I am looking to put a product filter plugin on my site so people can navigate better and find what they are looking for faster.

    I am wondering if you maybe know of any product filters like woof or premmerce that actually use min max quantity for product filtering?

    So i mean if people would select a productcategory, price and a quantity in 3 dropdowns in a sidebar that this productfilter would give correct search results.

    So let’s say the productcategory is bachelorparty the price/budget per person is €40,- and they are a group of 15.

    This product filter should be holding in account that the minimum quantity of this activity for a bachelorparty should be 15 or less and the max quantity can’t exceed 14 for the results that are shown.

    Do you know a productfilter that works like that?

    Kind regards,

    Dominic

    1. Hi Dominic,

      I am glad to know that this article was helpful to you. 🙂

      Honestly, I am not aware if such filters are available or not. Based on the requirements you have shared, I searched if anything related to this matter is already implemented or not. Unfortunately, I didn’t find anything which can help to achieve your business requirements.

  27. Do i put all of the code in child function.php? I put the first code there.. seems like max quatity works but not min

    1. Hi Stine,

      Yes, you have to put that code in the functions.php file of your currently active theme.

      Is the minimum quantity is still not working? Because I rechecked the code and it worked fine for me.

      1. Thank you for reply.. it works in astra theme functions.php but not in child theme.. so i have to put it back whenever i update the theme

        1. Hi Stine,

          You are welcome. 🙂 It’s strange that the code is not working when you are placing in the child theme. Let me know if there is any way I can help you to look into it so that you don’t have to place the code in the parent theme.

          1. Hi Stine,

            My email address is kartik at tychesoftwares dot com. I can look into it later today. I hope that is fine.

  28. Thank you very much, that’s an excellent tutorial!

    How difficult would it be to use the minimum quantity per product also as multiple for items sold in bulk? So minimum quantity = 6 and item can only be bought in multiples of 6?

    1. Hi,

      You are welcome. 🙂

      I don’t know how difficult it would be but if you can try the same code snippet along with the plugin you are using to sell items in bulk and if this snippet works then what would be better than that. Please let me know the results.

      However, I would also like to know which solution you are using to the sell the items in the bulk. So if I can help you with the code snippet then I will surely do that.

    1. Hi Edrick,

      No, this code will only work with the Simple product type. There are free and paid plugins available(listed in the post) which you can use if you wish to setup minimum and maximum quantity for different types of product.

      1. Hi,
        Thank you for the quick reply. Actually I want to set a minimum quantity for variable products regradless of variations. For eg: min qnty of 2 for all the variations of that product. Can i use this for that purpose?

          1. Thank you so much. I tried the plugin. It works but the only problem is that, in the product page the quantity selector is not showing the minimum set quantity. Instead it is showing default value (1). Otherwise its fine. Anyway thank you so much for such a great post!!!

          2. Hi Edrick,

            You are welcome. I am glad to know that provided information helped you to achieve your requirements. 🙂

  29. Thanks. This is awesome, and most importantly, it works! One suggestion:

    You should namespace your functions, e.g. ‘mytheme_wc_quantity_input_min_callback()’. Right now they have the same ‘wc_’ namespace as the Woocommerce functions, which is potentially problematic. It might also be a good idea to namespace the custom field keys.

    Thanks again.

    1. Hi Brad,

      You are welcome. And I am glad to know that it worked for you. 🙂

      You know what, mostly I use the prefix for the function name but in this post I missed it. 🙁

      No worries. Soon I will update the gist with the prefix to the function.

      Thank you for the suggestion. Have a great day. 😉

        1. Hi Rezart,

          I just rechecked the code snippet with the latest version of the WooCommerce and everything is working fine for me. It would be great if you can let me know how exactly you are trying to use this code and what issue you are facing so that it will help me to identify what is going wrong at your end.

          1. Yes, indeed it works. It seems the theme I was using had modified WoCcommerce hooks. Great job btw!!!

            ps: is there any way to make this work with variable products? Not talking about other plugins but make this code usable when variable selected also.

            Thank You! 🙂

          2. Hi Rezart,

            I am glad to know that it worked for you. 🙂

            Yes, I am going to write a separate post on setting minimum and maximum quantity for a variable product as well. Hopefully the same code I can reuse to achieve the same. Fingers crossed. 😉 Once the post is published then I will let you know of the same.

            Please let me know if you have any further questions or suggestions.

          3. Kartik, did you ever get around to doing the post for variations. Your original code is such a great help, I’m anxious to do the same with variations. Thanks for sharing.

          4. Hi Jim,

            I started but I could not spend more time on it so the post is still pending. But I have managed to create some snippets for it and I hope that might will help you in some sense. Below is the link for the code snippet which will add the Minumum & Maximum Input fields for each variation and apply the settings on the front end.
            Link: https://gist.github.com/kartikparmar/197cd898a0ee50f42cafe065d4405d99

            Please let me know if you have any further questions.

            : Kartik

          5. Kartik,

            Thanks for the help. Unfortunately, I’m having a problem with the code. When I try to add more of an item that is already in my cart, I’m getting the Woocommerce message “You can add a maximum of “item title” to your cart. You already have “number of items in cart.” None of the items has a maximum quantity set. Do you have any thoughts on what could cause this issue?

          6. Hi Jim,

            Ohh yes, I am able to replicate the same at my end. When no value set in the maximum quantity field then it is showing error notice when adding the product to cart. Applied the patch on line number 35 of the code snippet available on below link for validating the cart.
            Link: https://gist.github.com/kartikparmar/c07bb50c4b36f0e9ecc5b45f24c700f2

            Please do the changes and let me know if that resolves the issue or not.

            : Kartik

          7. Yes! It worked perfectly. Thank you very much for making this code available. You have provided a wonderful service that is helpful to many. I appreciate it very much.

            Thanks again,

            Jim

          8. Hi Jim,

            You are welcome. 🙂 I am glad to know that it works for you.

            The code snippet provided for the Minimum & Maximum Quantity for Variations is not thoroughly tested so it might be possible you may face some issues. So feel free to let me know if you face any issue.

            : Kartik

          9. Kartik,

            The single product code is working great. Today, I tried to use the minimum/maximum code you provided. Unfortunately, I got the white screen of death. Had to go into my file manager to delete the snippet. Not sure where things are conflicting, but everything works again when I disabled that snippet.

          10. Hi Jim,

            I apologize for the inconvenience you are facing. Would you mind sharing below admin level access details so that I can debug the issue? I would need access to your WordPress website and FTP details of it. Please share the same on below email address.
            Email Address: kartik at tychesoftwares dot com

          11. Hi Rezart, Kartik,
            First of all thanks Kartik for sharing this tuto.
            I am using Divi theme and put the code in the functions.php page of my child theme.
            I do see I am now able to add a min and a max in the “inventory” of all products but it doesn’t work when I got to test it.

            Rezart talked @ hooks (don’t really know what this is precisely). How can I check DIVI did or not change the WC hooks? And if it’s not the “hooks” , can you confirm this post is still up to date?

            Even I have a lot of interest in, I am not a computer/programmer guy. So it might be usful if you can see my functions.php page?

            Thanks a lot in advance for your suggestions

          12. Hi Andre,

            You are welcome. 🙂

            Yes, the code snippets are updated. I have not checked the same with the latest version DIVI theme so I am not sure why min and max are not being applied on the front end. I am assuming that you already know that this snippet will work only for the WooCommerce Simple Product type.

            If you can send the latest version of DIVI theme to below email address then I will check if the same thing is replicated at my end not. If replicated and that can be fixed quickly then I will get back to you with the patch for the same.
            Email Address: kartik at tychesoftwares dot com

    1. Hi,

      Thanks for the sharing the link. But like I have mentioned in this post that there are already the free plugins available on WordPress Repository then it is meaningless to purchase the plugin.

  30. Can you set max for Course? I don’t see an easy way to do this and my clients are mistakenly adding the course to their cart more than once.

    1. Have you gone through this post? It’s all about setting minimum and maximum quantity for product(course).

      You can use the code snippets shared in this post if you have some knowledge of coding or you can install the plug-in mentioned in this post to achieve your requirements.

      If you want your clients to add the product only once to their basket then WooCommerce has Sold Individually option available under Inventory tab of Product data meta box. Please let me know if that will help or not.

    1. Hi Eric,

      Not sure if by adding some more code, max quantity can be set by the country being shipped to or not.

      But you can check ‘Conditional Shipping and Payments’ plugin which allows adding conditions on product items based on shipping settings. You can contact plugin author for detailed information.
      Link: https://docs.woocommerce.com/document/woocommerce-conditional-shipping-and-payments/
      Screenshot: https://prnt.sc/j3nn1e

      Please let me know if you have any further questions.

      1. Unfortunately, minmax for Woocommerce Doesn’t work on a base level for Variable products. It only works when you have global settings, just like this one!

Leave a Reply to JoeBlack Cancel reply

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

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible.

Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

By using our site, you acknowledge that you have read and understood our Privacy Policy and Terms & Conditions.