Sell in Packs (Quantity Steps)
Makes products sell only in multiples, such as packs of 6, by setting the quantity step and checking the cart.
Opens WPIDE on
Code
$wpide_qty_step = 6; // Products can only be bought in multiples of this number.
add_filter( 'woocommerce_quantity_input_args', function ( $args, $product ) use ( $wpide_qty_step ) {
if ( $product->is_sold_individually() ) {
return $args;
}
$args['step'] = $wpide_qty_step;
$args['min_value'] = max( $wpide_qty_step, (int) $args['min_value'] );
if ( (int) $args['input_value'] < $wpide_qty_step ) {
$args['input_value'] = $wpide_qty_step;
}
return $args;
}, 10, 2 );
add_filter( 'woocommerce_add_to_cart_validation', function ( $passed, $product_id, $quantity ) use ( $wpide_qty_step ) {
if ( $quantity % $wpide_qty_step ) {
wc_add_notice( sprintf( 'This product is sold in packs of %d.', $wpide_qty_step ), 'error' );
return false;
}
return $passed;
}, 10, 3 );
add_action( 'woocommerce_check_cart_items', function () use ( $wpide_qty_step ) {
foreach ( WC()->cart->get_cart() as $item ) {
if ( ! $item['data']->is_sold_individually() && $item['quantity'] % $wpide_qty_step ) {
wc_add_notice( sprintf( '"%1$s" is sold in packs of %2$d. Please adjust the quantity.', $item['data']->get_name(), $wpide_qty_step ), 'error' );
}
}
} );
Notes
Change $step. The minimum quantity becomes one pack.
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.