WooCommerce: Check if coupon is valid
I believe the most recent method encouraged by WooCommerce is using the \WC_Discounts Class. Here is an example:
function is_referral_coupon_valid( $coupon_code ) { $coupon = new \WC_Coupon( $coupon_code ); $discounts = new \WC_Discounts( WC()->cart ); $valid_response = $discounts->is_coupon_valid( $coupon ); if ( is_wp_error( $valid_response ) ) { return false; } else { return true; }}
It's important to remember doing that inside the wp_loaded hook at least, like this:
add_action( 'wp_loaded', function(){ is_referral_coupon_valid('my-coupon-code');});
UPDATE
Now I believe this simpler method using is_valid() could also work but I haven't tested it myself:
$coupon = new WC_Coupon( 'my-coupon-code' );$coupon->is_valid();
$code = 'test123';$coupon = new WC_Coupon($code);$coupon_post = get_post($coupon->id);$coupon_data = array( 'id' => $coupon->id, 'code' => $coupon->code, 'type' => $coupon->type, 'created_at' => $coupon_post->post_date_gmt, 'updated_at' => $coupon_post->post_modified_gmt, 'amount' => wc_format_decimal($coupon->coupon_amount, 2), 'individual_use' => ( 'yes' === $coupon->individual_use ), 'product_ids' => array_map('absint', (array) $coupon->product_ids), 'exclude_product_ids' => array_map('absint', (array) $coupon->exclude_product_ids), 'usage_limit' => (!empty($coupon->usage_limit) ) ? $coupon->usage_limit : null, 'usage_count' => (int) $coupon->usage_count, 'expiry_date' => (!empty($coupon->expiry_date) ) ? date('Y-m-d', $coupon->expiry_date) : null, 'enable_free_shipping' => $coupon->enable_free_shipping(), 'product_category_ids' => array_map('absint', (array) $coupon->product_categories), 'exclude_product_category_ids' => array_map('absint', (array) $coupon->exclude_product_categories), 'exclude_sale_items' => $coupon->exclude_sale_items(), 'minimum_amount' => wc_format_decimal($coupon->minimum_amount, 2), 'maximum_amount' => wc_format_decimal($coupon->maximum_amount, 2), 'customer_emails' => $coupon->customer_email, 'description' => $coupon_post->post_excerpt,);$usage_left = $coupon_data['usage_limit'] - $coupon_data['usage_count'];if ($usage_left > 0) { echo 'Coupon Valid';} else { echo 'Coupon Usage Limit Reached';}
The code is tested and fully functional.
Reference