WooCommerce: Check if coupon is valid

NuclearApe picture NuclearApe · Sep 28, 2016 · Viewed 11.3k times · Source

I am trying to check if a coupon is still valid (hasn't reached its usage limit) and display content under this condition.

The reason for this is that I want to be able to hand out a coupon code to particular visitors, but obviously don't want to hand out a coupon that has already reached it's usage limit.

I am trying to achieve this with PHP and imagine the code to be something like this:

<?php if (coupon('mycouponcode') isvalid) {
  echo "Coupon Valid"
} else {
  echo "Coupon Usage Limit Reached"
} ?>

Any help here would be great :)

Answer

Pablo S G Pacheco picture Pablo S G Pacheco · Sep 18, 2018

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();