Minimum Purchase Quantity per Product
Requires shoppers to buy at least a set number of each product, for example 2, and sets the quantity box to start at that number.
Opens WPIDE on
Code
$wpide_min_qty = array(
'minimum' => 2, // Minimum units per product.
'product_ids' => array(), // Limit to these product IDs, empty for all.
);
$wpide_min_qty_applies = function ( $product_id ) use ( $wpide_min_qty ) {
return empty( $wpide_min_qty['product_ids'] ) || in_array( (int) $product_id, array_map( 'intval', $wpide_min_qty['product_ids'] ), true );
};
add_filter( 'woocommerce_quantity_input_args', function ( $args, $product ) use ( $wpide_min_qty, $wpide_min_qty_applies ) {
$id = $product->get_parent_id() ? $product->get_parent_id() : $product->get_id();
if ( $product->is_sold_individually() || ! $wpide_min_qty_applies( $id ) ) {
return $args;
}
$args['min_value'] = $wpide_min_qty['minimum'];
if ( ! is_cart() && (int) $args['input_value'] < $wpide_min_qty['minimum'] ) {
$args['input_value'] = $wpide_min_qty['minimum'];
}
return $args;
}, 10, 2 );
add_action( 'woocommerce_check_cart_items', function () use ( $wpide_min_qty, $wpide_min_qty_applies ) {
foreach ( WC()->cart->get_cart() as $item ) {
$product = $item['data'];
if ( $product->is_sold_individually() || ! $wpide_min_qty_applies( $item['product_id'] ) ) {
continue;
}
if ( (int) $item['quantity'] < $wpide_min_qty['minimum'] ) {
wc_add_notice( sprintf( 'Please order at least %1$d of "%2$s".', $wpide_min_qty['minimum'], $product->get_name() ), 'error' );
}
}
} );
Notes
Change $minimum. Add product IDs to $product_ids to apply the rule only to those products; leave it empty for all products.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.