/** * Sets which coupons should be applied for this calculation. * * This function is hooked to "woocommerce_before_calculate_totals" so that WC will calculate a subscription * product's total based on the total of it's price per period and sign up fee (if any). * * @since 1.3.5 */ public static function remove_coupons($cart) { global $woocommerce; $calculation_type = WC_Subscriptions_Cart::get_calculation_type(); // Only hook when totals are being calculated completely (on cart & checkout pages) if ('none' == $calculation_type || !WC_Subscriptions_Cart::cart_contains_subscription() || !is_checkout() && !is_cart() && !defined('WOOCOMMERCE_CHECKOUT') && !defined('WOOCOMMERCE_CART')) { return; } $applied_coupons = $cart->get_applied_coupons(); // If we're calculating a sign-up fee or recurring fee only amount, remove irrelevant coupons if (!empty($applied_coupons)) { // Keep track of which coupons, if any, need to be reapplied immediately $coupons_to_reapply = array(); if (in_array($calculation_type, array('combined_total', 'sign_up_fee_total', 'recurring_total'))) { foreach ($applied_coupons as $coupon_code) { $coupon = new WC_Coupon($coupon_code); if (in_array($coupon->type, array('recurring_fee', 'recurring_percent'))) { // always apply coupons to their specific calculation case if ('recurring_total' == $calculation_type) { $coupons_to_reapply[] = $coupon_code; } elseif ('combined_total' == $calculation_type && !WC_Subscriptions_Cart::cart_contains_free_trial()) { // sometimes apply recurring coupons to initial total $coupons_to_reapply[] = $coupon_code; } else { self::$removed_coupons[] = $coupon_code; } } elseif (in_array($calculation_type, array('combined_total', 'sign_up_fee_total', 'none')) && !in_array($coupon->type, array('recurring_fee', 'recurring_percent'))) { // apply all coupons to the first payment $coupons_to_reapply[] = $coupon_code; } else { self::$removed_coupons[] = $coupon_code; } } // Now remove all coupons (WC only provides a function to remove all coupons) $cart->remove_coupons(); // And re-apply those which relate to this calculation $woocommerce->cart->applied_coupons = $coupons_to_reapply; } } }