25% off ProSNIPC25OFF

Set Minimum Order Quantity per Product

Reads a per-product minimum quantity meta value and enforces it on the quantity input and at add-to-cart validation.

PHPby SnipCraft
php
<?php
if ( ! class_exists( 'WooCommerce' ) ) {
    return;
}

/**
 * Store the desired minimum as _scseed_min_qty on each product (integer >= 2).
 * Products without this meta default to quantity 1.
 */
add_filter( 'woocommerce_quantity_input_args', 'scseed_min_qty_input_args', 10, 2 );
function scseed_min_qty_input_args( $args, $product ) {
    $min = absint( get_post_meta( $product->get_id(), '_scseed_min_qty', true ) );
    if ( $min > 1 ) {
        $args['min_value'] = $min;
        if ( (int) $args['input_value'] < $min ) {
            $args['input_value'] = $min;
        }
    }
    return $args;
}

add_filter( 'woocommerce_add_to_cart_validation', 'scseed_validate_min_qty', 10, 3 );
function scseed_validate_min_qty( $passed, $product_id, $quantity ) {
    $min = absint( get_post_meta( $product_id, '_scseed_min_qty', true ) );
    if ( $min > 1 && (int) $quantity < $min ) {
        $product = wc_get_product( $product_id );
        wc_add_notice(
            sprintf(
                /* translators: 1: product name, 2: minimum quantity */
                esc_html__( 'The minimum order quantity for "%1$s" is %2$d.', 'scseed' ),
                $product ? esc_html( $product->get_name() ) : '',
                $min
            ),
            'error'
        );
        return false;
    }
    return $passed;
}
#cart#products#quantity#validation#woocommerce