Skip to content

Instantly share code, notes, and snippets.

@mikeyarce
Created September 12, 2020 06:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeyarce/f19d4b8601644212f734608d9bbf72a9 to your computer and use it in GitHub Desktop.
Save mikeyarce/f19d4b8601644212f734608d9bbf72a9 to your computer and use it in GitHub Desktop.
Set a maximum quantity for a product in WooCommerce
<?php // only add this line if it's at the top of a new PHP file
add_filter( 'woocommerce_add_to_cart_validation', 'validate_add_to_cart_action', 10, 3 );
function validate_add_to_cart_action( $valid, $product_id, $quantity ) {
// Set the product ID for the product you want to limit
$check_product_id = 121;
// We want to check two quantities, the current cart and how many you are currently adding. We're going to be adding them together into one variable called total_quantity.
$total_quantity = $quantity;
$maximum_quantity = 2;
// Setting the default to valid
$valid = true;
// Checking if it's the product ID we want to target
if ( $check_product_id === $product_id ) {
// Loop through the items in the cart first
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
// If the item in the cart matches our product id, we'll add the current cart quantity to our total quantity
if ( $values['product_id'] === $check_product_id ) {
$total_quantity += $values['quantity'];
}
}
// Let's check our total quantity now and see if it's above our maximum - if so, we'll display an error message
if ( $total_quantity > 0 && $total_quantity > $maximum_quantity ) {
// Grab the product object so we can output which product has the issue
$_product = wc_get_product( $product_id );
$message = sprintf( 'You can only have a maximum quantity of %d for the %s product (you currently have %d in your cart).', $maximum_quantity, $_product->get_title(), $total_quantity - $quantity );
wc_add_notice( $message, 'error' );
$valid = false;
}
}
return $valid;
}
add_action( 'woocommerce_check_cart_items', 'set_max_for_cart_item' );
function set_max_for_cart_item() {
// Set the product ID for the product you want to limit
$check_product_id = 121;
// Set the maximum quantity
$maximum_quantity = 2;
// Loop through the Cart items
foreach ( WC()->cart->get_cart() as $key => $values ) {
$_product = $values['data'];
// Check for the speicifc product
if ( $check_product_id === $values['product_id'] && $values['quantity'] > $maximum_quantity ) {
// If we match the product, we set an error message
$message = sprintf( __( 'You can only have a maximum of %d for the product "%s".' ), $maximum_quantity, $_product->get_title() );
wc_add_notice( $message, 'error' );
return;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment