Categories : PHP , Wordpress
woocommerce add to cart hook to dont allow user to add cart less than "_min_quantity" product meta for wordpress

min quantity plugin example

If you want to dont allow user to add cart less than pack you can use this hook for it.

You can add this hook and function to functions.php of your theme or plugin.

This hook uses woocommerce_add_to_cart


add_action(
    'woocommerce_add_to_cart',
    'gc_add_to_cart_validation',
    10,
    6
);

function gc_add_to_cart_validation($product_id, $quantity, $variation_id = '', $variation = '', $cart_item_data = array())
{
    $product = wc_get_product($product_id);

    if ($product->is_type('variable')) {
        $variations = $product->get_available_variations();
        foreach ($variations as $variation) {
            if ($variation["attributes"]["attribute_pa_produkt-einheit"] == "kolli") {
                $min_quantity = get_post_meta($product_id, "_min_quantity", true);
                if ($quantity < $min_quantity) {
                    wc_add_notice(
                        sprintf(
                            __('You can not add less than %s kolli', 'woocommerce'),
                            $min_quantity
                        ),
                        'error'
                    );
                }
            }
        }
    } else {
        $min_quantity = get_post_meta($product_id, "_min_quantity", true);
        if ($quantity < $min_quantity) {
            wc_add_notice(
                sprintf(
                    __('You can not add less than %s kolli', 'woocommerce'),
                    $min_quantity
                ),
                'error'
            );
        }
    }
}

Leave a Reply

Your email address will not be published.