Reputation: 570
I want to restrict add to cart button with a max quantity of 10 per product. I want customers cannot purchase more than 10 quantity per product per order.
Here is the code
add_filter( 'woocommerce_add_to_cart_validation', 'restrict_per_product_quantity' );
function restrict_per_product_quantity($cart_item_data) {
global $woocommerce;
$item_count = $woocommerce->cart->cart_contents_count;
if($item_count > 10) {
wc_add_notice( 'Sorry, Only 10 quantity per product per order is allowed. If you would like to order more please contact support.', 'error' );
return false;
}
return $cart_item_data;
}
The issue is this code did not work with per product, it checks the cart, and if there are 10 items in the cart it displays the error.
Upvotes: 3
Views: 2796
Reputation: 108
Use these hooks to set minimum and maximum Quantity for product.
<?php
/*
* Changing the minimum quantity to 2 for all the WooCommerce products
*/
function woocommerce_quantity_input_min_callback( $min, $product ) {
$min = 2;
return $min;
}
add_filter( 'woocommerce_quantity_input_min', 'woocommerce_quantity_input_min_callback', 10, 2 );
/*
* Changing the maximum quantity to 5 for all the WooCommerce products
*/
function woocommerce_quantity_input_max_callback( $max, $product ) {
$max = 5;
return $max;
}
add_filter( 'woocommerce_quantity_input_max', 'woocommerce_quantity_input_max_callback', 10, 2 );
?>
[![enter image description here][1]][1]
Upvotes: 0
Reputation: 29660
woocommerce_add_to_cart_validation
contains 5 parameters that you can usefunction filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
// Set max allowed
$max_allowed = 10;
// Error message
$message = 'max ' . $max_allowed . ' products allowed';
// quantity > max allowed || elseif = when cart not empty
if ( $quantity > $max_allowed ) {
wc_add_notice( __( $message, 'woocommerce' ), 'error' );
$passed = false;
} elseif ( ! WC()->cart->is_empty() ) {
// Get current product id
$product_id = $variation_id > 0 ? $variation_id : $product_id;
// Cart id
$product_cart_id = WC()->cart->generate_cart_id( $product_id );
// Find product in cart
$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
// True
if ( $in_cart ) {
// Get cart
$cart = WC()->cart->get_cart();
// Current quantity in cart
$quantity_in_cart = $cart[$product_cart_id]['quantity'];
// Condition: quanitity in cart + new add quantity greater than max allowed
if ( $quantity_in_cart + $quantity > $max_allowed ) {
wc_add_notice( __( $message, 'woocommerce' ), 'error' );
$passed = false;
}
}
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );
Upvotes: 5