How to restrict users to order product in multiples of an quantity Woocommerce?

We often come up with a store or scenario where we need to sell products in multiples. For example a dozen of eggs which will be multiple of 12, pack of candles which could be 3,6,12.

In this tutorial we’ll learn how to restrict users to order products in multiple of n quantity, where n could be any number.

By default there is no check of such kind in woocommerce. Let’s say we want our store to allow users to order products in multiples of 5 only.

To do this add the following lines of code at the end of your theme’s functions.php file:

add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities' );

function woocommerce_check_cart_quantities() {

global $woocommerce;

$multiples = 5;

   $total_products = 0;

   foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {

       $total_products += $values['quantity'];

   }

   if ( ( $total_products % $multiples ) > 0 )

       $woocommerce->add_error( sprintf( __('You need to buy in quantities of %s products', 'woocommerce'), $multiples ) );

}

Replace the value of $multiples with any value of your choice.

You can access the functions.php file here:

woocommerceSave the file by clicking on update file button after placing the above file.

Now add a product to cart and navigate to cart page by clicking on view cart button.

woocommerceHere you’ll see a warning if the product quantity is not a multiple of 5.

woocommerceEven if you click on proceed to checkout button it won’t allow you to move any further.

woocommerceWhen the order quantity will be multiple of 5 the error message being displayed will be removed and user can proceed to checkout.

woocommerceCHEERS J

Waqas

I hope you enjoy reading this blog post. If you want my team to do WooCommerce Maintenance for you, click here.

Leave a Comment

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