Skip to content

Instantly share code, notes, and snippets.

@riotxoa
Created August 28, 2018 07:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save riotxoa/f4f1a895052c195394ba4841085a0e83 to your computer and use it in GitHub Desktop.
Save riotxoa/f4f1a895052c195394ba4841085a0e83 to your computer and use it in GitHub Desktop.
WooCommerce Coupons Fix: email restrictions
/*
WooCommerce email restriction for coupons does not work. This fix corrects it.
Include this code snippet in your theme or plugin.
*/
add_filter( 'woocommerce_coupon_is_valid', 'wc_riotxoa_coupon_is_valid', 10, 2 );
if ( ! function_exists( 'wc_riotxoa_coupon_is_valid' ) ) {
function wc_riotxoa_coupon_is_valid( $result, $coupon ) {
$user = wp_get_current_user();
$restricted_emails = $coupon->get_email_restrictions();
return ( in_array( $user->user_email, $restricted_emails ) ? $result : false );
}
}
@bignevola
Copy link

bignevola commented Oct 1, 2018

Doesn't work for new wildcard email restriction with asterisk (*@gmail.com).

@urkaGR
Copy link

urkaGR commented Nov 19, 2018

If I insert this in 3.5.1 restriction works BUT I no coupon works without any restriction email!!
Anybody an idea what to change if you have both online at the same time? (some with restriction and some without)

@bhrng
Copy link

bhrng commented Jul 18, 2019

Although its been a while, maybe this is helpful for someone:
Simply check whether there are e-mails in the $restricted_emails array by counting its elements. Did the trick for me:

`

    add_filter ( 'woocommerce_coupon_is_valid', 'wc_riotxoa_coupon_is_valid', 10, 2 );

if ( !function_exists ( 'wc_riotxoa_coupon_is_valid' ) ) {
	function wc_riotxoa_coupon_is_valid( $result, $coupon ) {
		$user = wp_get_current_user();
		$restricted_emails = $coupon->get_email_restrictions();
		
		if ( count ( $restricted_emails ) > 0 ){
			if ( in_array ( $user->user_email, $restricted_emails ) ) {
				return $result;
			} else {
				return false;
			}

		} else {
			return $result;
		}
	}
}

`

@saulopaiva
Copy link

In addiction to the discussion, if needed to verify wildcard restrictions. Example *@gmail.com.

It is possible to use a function of WC_Cart: is_coupon_emails_allowed:

add_filter('woocommerce_coupon_is_valid', function ($result, $coupon) {
    if (null === WC()->cart) {
        return $result;
    }

    $user = wp_get_current_user();
    $restricted_emails = $coupon->get_email_restrictions();

    if (count($restricted_emails) > 0) {
        return WC()->cart->is_coupon_emails_allowed(
            [$user->user_email],
            $restricted_emails
        );
    } else {
        return $result;
    }
}, 10, 2);

@limonfresh
Copy link

Thank you @saulopaiva!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment