Search code examples
phpvalidationwoocommercecouponwoocommerce-subscriptions

Check programmatically if a coupon is valid for a user in WooCommerce


I'm programmatically applying a coupon to a subscription via a custom dashboard form so the user doesn't go through the standard cart to apply it. All it's doing is taking the code they've entered into an input then applying it to the sub.

Is there a way to validate the coupon against the user in the same way the cart performs a tonne of validation (like if the coupon has been used, can be a recurring coupon etc etc).

Is there a way to hook into that validation rather than me manually writing out all the different checks? It feels wrong doing it this way and likely that things will slip through the net.

I've got some basic checks in there like if the coupon exists, then the usage limit check.

$subscription = new WC_Subscription( $_REQUEST['sub_id'] );
$coupon_code = $_REQUEST['voucher_code'];
$coupon = new WC_Coupon( $coupon_code );
if ($coupon->is_valid()) {

    $coupon_type = $coupon->get_discount_type();
    $coupon_amount = $coupon->get_amount();
    $total = $subscription->get_total();

    if($coupon->get_usage_count() < $coupon->get_usage_limit() || $coupon->get_usage_limit() == ""){
        $strcode = strtolower($coupon_code);
        foreach ( $coupons as $coupon ) {
            if($coupon->get_code() == $strcode){
                $subscription->remove_coupon( $coupon->get_code() );
            }
        }
        $subscription->apply_coupon( $coupon_code );
        $note = "Coupon " . $coupon_code . " has been applied to subscription";
        $subscription->add_order_note( $note );
        $subscription->calculate_totals();
    }
}

Solution

  • The WC_Coupon method is_valid() does everything itself, as it uses WC_Discount method is_coupon_valid() that checks if coupon is valid for the user.

    So you doesn't need anything more than you have already done in your code.