Limit maximum quantity of free products in Woocommerce cart
My client has asked for the ability to offer free samples of their variable products on their Woocommerce online store, with a maximum of 1 of each unique product sample and 5 of any of the samples on their order.
I’ve achieved part of this by adding an extra “Free Sample” variation to each product and then using a free Min/Max quantity plugin to limit the amount of each individual free sample to 1 per order, please see the following screenshots:
https://ibb.co/f0Wd7XC https://ibb.co/8DrsZZj
So far I haven’t established a way to limit the maximum number of any combination of the “Free Sample” variations to 5 though. The only way I can see is by limiting the total number of free products (i.e. price = £0) per order to 5, or alternatively by assigning a specific shipping class to each variation (i.e.”Free Samples”) and then somehow limiting the amount of products assigned with this shipping class in each order to 5. Is this possible?
Cheers,
M.
Solutions
Woocommerce have validation hook which you can use.
First one is when we add to our cart
function add_to_cart_free_samples($valid, $product_id, $quantity) {
$max_allowed = 5;
$current_cart_count = WC()->cart->get_cart_contents_count();
foreach (WC()->cart->get_cart() as $cart_item_key=>$cart_item ){
// Here change attribute group if needed - currently assigned to default size attribute
$variation = $cart_item['variation']['attribute_pa_size'];
}
if( ( $current_cart_count > $max_allowed || $current_cart_count + $quantity > $max_allowed ) && $variation === 'free-sample' && $valid ){
wc_add_notice( sprintf( __( 'Whoa hold up. You can only have %d items in your cart', 'your-textdomain' ), $max_allowed ), 'error' );
$valid = false;
}
return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'add_to_cart_free_samples', 10, 3 );
Second one is when we update the cart on cart page for example.
function update_add_to_cart_free_samples( $passed, $cart_item_key, $values, $updated_quantity ) {
$cart_items_count = WC()->cart->get_cart_contents_count();
$original_quantity = $values['quantity'];
$max_allowed = 5;
$total_count = $cart_items_count - $original_quantity + $updated_quantity;
foreach (WC()->cart->get_cart() as $cart_item_key=>$cart_item ){
// Here change attribute group if needed - currently assigned to default size attribute
$variation = $cart_item['variation']['attribute_pa_size'];
}
if( $cart_items_count > $max_allowed && $variation === 'free-sample' ){
$passed = false;
wc_add_notice( sprintf( __( 'Whoa hold up. You can only have %d items in your cart', 'your-textdomain' ), $max_allowed ), 'error' );
}
return $passed;
}
add_filter( 'woocommerce_update_cart_validation', 'update_add_to_cart_free_samples', 10, 4 );
In $cart_item you can debug and see all info for the current product in the cart. From there you can add condition depending on shipping or attribue or price or w/e you want.