/** * Check is a subscription coupon is valid before applying * * @since 1.2 */ public static function validate_subscription_coupon($valid, $coupon) { self::$coupon_error = ''; // ignore non-subscription coupons if (!in_array($coupon->type, array('recurring_fee', 'sign_up_fee', 'recurring_percent', 'sign_up_fee_percent'))) { // make sure there are no other products in the cart which the coupon could be applied to - WC()->cart->get_cart_contents_count() returns the quantity of items in the cart, not the total number of unique items, we need to use WC()->cart->cart_contents for that. if (1 == count(WC()->cart->cart_contents) && 0 == WC_Subscriptions_Cart::get_cart_subscription_sign_up_fee()) { $error_message = __('Sorry, this coupon is only valid for an initial payment and the subscription does not have an initial payment.', 'woocommerce-subscriptions'); // now make sure there is actually something for the coupon to be applied to (i.e. not a free trial or sync'd subscription without any prorated initial amount) if (WC_Subscriptions_Cart::cart_contains_free_trial()) { self::$coupon_error = $error_message; } elseif (WC_Subscriptions_Synchroniser::cart_contains_synced_subscription() && !WC_Subscriptions_Synchroniser::cart_contains_prorated_subscription()) { self::$coupon_error = $error_message; } } } else { // prevent subscription coupons from being applied to renewal payments if (WC_Subscriptions_Cart::cart_contains_subscription_renewal('child')) { self::$coupon_error = __('Sorry, this coupon is only valid for new subscriptions.', 'woocommerce-subscriptions'); } // prevent subscription coupons from being applied to non-subscription products if (!WC_Subscriptions_Cart::cart_contains_subscription_renewal() && !WC_Subscriptions_Cart::cart_contains_subscription()) { self::$coupon_error = __('Sorry, this coupon is only valid for subscription products.', 'woocommerce-subscriptions'); } // prevent sign up fee coupons from being applied to subscriptions without a sign up fee if (0 == WC_Subscriptions_Cart::get_cart_subscription_sign_up_fee() && in_array($coupon->type, array('sign_up_fee', 'sign_up_fee_percent'))) { self::$coupon_error = __('Sorry, this coupon is only valid for subscription products with a sign-up fee.', 'woocommerce-subscriptions'); } } if (!empty(self::$coupon_error)) { $valid = false; add_filter('woocommerce_coupon_error', __CLASS__ . '::add_coupon_error', 10); } return $valid; }