Limit Cart Quantity per Product

This snippet limits the quantity of each product that can be added to the cart, useful for managing inventory or promotions.

PHP

function limit_cart_quantity_per_product( $passed, $product_id, $quantity, $variation_id = null ) {
    $max_allowed = 5; // Set your maximum allowed quantity here
    $cart_quantity = WC()->cart->get_cart_item_quantities();

    if ( isset( $cart_quantity[$product_id] ) && ( $cart_quantity[$product_id] + $quantity > $max_allowed ) ) {
        wc_add_notice( sprintf( 'You can only purchase a maximum of %s of this item.', $max_allowed ), 'error' );
        return false;
    }
    return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'limit_cart_quantity_per_product', 10, 4 );

Snippet Feedback

Did this snippet work for you? Do you have any questions about this snippet? Leave some feedback below.
SHARED BY

4 Views

Tags

Language

Did it work?

Save Snippet

Embed Snippet

To embed this snippet on your site, copy this html code and paste into your webpage. Learn more
By embedding snippets on your site, you are agreeing to our terms and conditions.

Embed Snippet

To embed this snippet on your site, copy this html code and paste into your webpage. Learn more
By embedding snippets on your site, you are agreeing to our terms and conditions.

Embed Snippet

To embed this snippet on your site, copy this html code and paste into your webpage. Learn more
By embedding snippets on your site, you are agreeing to our terms and conditions.