Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.