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