I am trying to automatically trigger a coupon to be applied in the cart specifically for when there are 4 items in the cart.
The coupon is pre-created in the Woocommerce back-end of the site "tasterbox"
I am using an amended version from this answer code:
Add WooCommerce coupon code automatically based on product categories
Here is my code version:
add_action( 'woocommerce_before_calculate_totals', 'wc_auto_add_coupons', 10, 1 );
function wc_auto_add_coupons( $cart_object ) {
// Coupon code
$coupon = 'tasterbox';
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Initialising variables
$is_match = false;
$taster_item_count = 4;
// Iterating through each cart item
foreach ( WC()->cart->get_cart() as $cart_item ) {
// If cart items match 4
if( $cart->cart_contents_count == $taster_item_count ){
$is_match = true; // Set to true
break; // stop the loop
}
}
// If conditions are matched add the coupon discount
if( $is_match && ! $cart_object->has_discount( $coupon )){
// Apply the coupon code
$cart_object->add_discount( $coupon );
// Optionally display a message
wc_add_notice( __('TASTER BOX ADDED'), 'notice');
}
// If conditions are not matched and coupon has been appied
elseif( ! $has_category && $cart_object->has_discount( $coupon )){
// Remove the coupon code
$cart_object->remove_coupon( $coupon );
// Optionally display a message
wc_add_notice( __('SORRY, TASTERBOX NOT VALID'), 'alert');
}
}
However I can not get it to auto apply the coupon when there are 4 items in the cart. It seems like something simple to do, but I'm stuck.
Any help appreciated.