WooCommerce coupon for logged in user only

Use WooCommerce hook woocommerce_coupon_is_valid to check if coupon is valid.

Example shows how to make sure certain coupons are valid for logged in users only.
Same example can be use to extend validation, for example using global $current_user would allow you to validate any user information, eg: restrict coupon based on user role.

2 Comments

  1. Great code! Thanks you so much.

    One question:

    how I print a custom notices when return false instead default error message? I trying this but notices is added not changed.

    wc_add_notice( __( ‘Coupon only for logged users.’, ‘woocommerce’ ), ‘error’ );

    Thanks again.

    1. Hi JR, to be honest not sure.
      You can try with a filter instead woocommerce_add_error.
      That would look something like:

      add_filter('woocommerce_add_error', function ($message) {
      if ( 'default-returned-text' == $message ) {
      return 'My custom message';
      }
      return $message;
      }, 10 );

      Or maybe try with woocommerce_coupon_error.

      add_filter('woocommerce_coupon_error', function ( $message, $error_code, $coupon ) {
      return 'My custom message';
      }, 10, 3 );

      Note that this function accepts 3 params so you can test for error code/coupon to return custom text for specific coupons only.
      Hope that helps!

Leave a Reply

Your email address will not be published. Required fields are marked *