I am trying to set up a custom coupon code so that customers can add an add-on product to their cart, only if their cart total is $50 or more.
I am using Allow add to cart for specific products based on cart total in WooCommerce answer code that allows or denies adding the product depending on their cart total and this is working great.
My issue is that I have another bit of code that is supposed to delete the addon item if it's in the cart and the cart total is no longer within the threshold.
In my case I have the threshold set to $50, and the addon product costs $10.
In testing I've found that when the cart total is $60 or more, everything works fine. I can even remove a couple of items from the cart and the addon item will stay until the total is under the threshold, then it gets removed as well.
However if the cart total is anywhere between $50 and $60 when I go to add the addon item, the addon item is immediately deleted as soon as it's added.
I would expect the order of operations to go
- Checks the cart total, finds that it is above $50
- Allows me to add the addon item
- Checks the cart total with the addon item included, finds that it is now above $60
- Allows the addon to stay
Based on Add or remove specific cart Item based on WooCommerce cart total answer code, here is the code I'm using:
add_action( 'woocommerce_before_calculate_totals', 'add_or_remove_cart_items', 10, 1 );
function add_or_remove_cart_items( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// ONLY for logged users (and avoiding the hook repetition)
if ( ! is_user_logged_in() && did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$threshold_amount = 50; // The threshold amount for cart total
$addon_product_id = 7039; // ID of the addon item
$addon_product_cost = 10; // Cost of addon item
$cart_items_total = 0; // Initializing
$threshold_amount_with_addon = $threshold_amount + $addon_product_cost;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
// Check if the free product is in cart
if ( $cart_item['data']->get_id() == $addon_product_id ) {
$addon_item_key = $cart_item_key;
}
// Get cart subtotal incl. tax from items (with discounts if any)
$cart_items_total += $cart_item['line_total'] + $cart_item['line_tax'];
}
// If cart total is below the defined amount and addon product is in cart, we remove it.
if ( $cart_items_total < $threshold_amount_with_addon && isset($addon_item_key) ) {
$cart->remove_cart_item( $addon_item_key );
return;
}
}
I can't for the life of me figure out what is going wrong. Any help would be much appreciated.