Your cart is currently empty!
How To Only Allow 1 Variation of a Product Added To Cart
โ
by
Add this PHP code to the end of your child themes functions file or custom functionality plugin to restrict a specific variable product so only 1 variation can be added to cart.
Swap out the 13 in the following PHP code with the product ID you want to restrict.
add_filter('woocommerce_add_to_cart_validation', 'wpsitesdotnet_restrict_single_variation_in_cart', 10, 5);
function wpsitesdotnet_restrict_single_variation_in_cart($passed, $product_id, $quantity, $variation_id = 0, $variations = []) {
$specific_product_id = 13;
if ( $product_id == $specific_product_id ) {
foreach (WC()->cart->get_cart() as $cart_item) {
if ($cart_item['product_id'] == $specific_product_id && $cart_item['variation_id'] != $variation_id) {
wc_add_notice(__('You can only add one variation of this product to the cart.', 'woocommerce'), 'error');
return false;
}
}
}
return $passed;
}
When a customer tries to add more than 1 variation to cart, they get stopped and a notice displays this message “You can only add one variation of this product to the cart”.
The code enables you to :
- Target a specific variable product.
- Customize the error notice that displays when a customer tries to add more than one variation to their cart.
Related Solutions
Free
$0
Access only to all free tutorials per month.
Tutorial Request
Includes code guarantee and coding support.
Monthly
$75
Access to 10 premium tutorials per month.
Tutorial Request
Includes code guarantee and coding support.
Yearly
$500
Access to 15 premium tutorials per month.
Monthly Tutorial Request
Includes code guarantee and priority coding support.
Was This Tutorial Helpful?