Created
August 28, 2018 07:57
-
-
Save riotxoa/f4f1a895052c195394ba4841085a0e83 to your computer and use it in GitHub Desktop.
WooCommerce Coupons Fix: email restrictions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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 ); | |
} | |
} |
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)
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;
}
}
}
`
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);
Thank you @saulopaiva!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Doesn't work for new wildcard email restriction with asterisk (*@gmail.com).