I am trying to add one of three coupons to the cart automatically based on the cart subtotal ($250 or more; $150-249.99; and $75-149.99). This is what I have, but it makes the cart just spin when you update an item quantity in the cart. It seems to work when an additional new item is added to the cart or when an item in the cart is removed. However, when I increased the quantity of one item to move from the smallest discount to the medium discount, the cart page didn't load at all (it was blank). It was still blank even after I went and added a new product to the cart. I had to comment out the action to get it to load the cart.
I'd appreciate any help.
This works, except that when the cart is updated, it just spins. If you refresh, the correct discount displays (and the item count that was changed was updated.) Any idea why it would just spin like this?
add_action( 'woocommerce_before_calculate_totals', 'sbs_auto_add_coupons_total_based', 10, 1 );
function sbs_auto_add_coupons_total_based( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$coupon_15 = 'dicount15';
$coupon_10 = 'discount10';
$coupon_5 = 'discount5';
$applied_coupons = $cart->get_applied_coupons();
$subtotal = 0;
foreach( $cart->get_cart() as $cart_item ) {
$subtotal += $cart_item['line_subtotal'];
}
if( $subtotal >= 250 && ! in_array($coupon_15, $applied_coupons ) ){
if( in_array($coupon_10, $applied_coupons ) )
$cart->remove_coupon( $coupon_10 );
if( in_array($coupon_5, $applied_coupons ) )
$cart->remove_discount($coupon_5);
$cart->add_discount( $coupon_15 );
}
elseif( $subtotal >= 150 && ! in_array($coupon_10, $applied_coupons ) ) {
if( in_array($coupon_15, $applied_coupons ) )
$cart->remove_coupon( $coupon_15 );
if( in_array($coupon_5, $applied_coupons ) )
$cart->remove_discount($coupon_5);
$cart->add_discount( $coupon_15 );
}
elseif( $subtotal >= 75 && ! in_array($coupon_5, $applied_coupons ) ) {
if( in_array($coupon_15, $applied_coupons ) )
$cart->remove_coupon( $coupon_15 );
if( in_array($coupon_10, $applied_coupons ) )
$cart->remove_discount($coupon_10);
$cart->add_discount( $coupon_5 );
}
else {
if( in_array($coupon_15, $applied_coupons ) )
$cart->remove_coupon( $coupon_15 );
if( in_array($coupon_10, $applied_coupons ) )
$cart->remove_discount($coupon_10);
if( in_array($coupon_5, applied_coupons ) )
$cart->remove_discount($coupon_5);
}
}