Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save BrianHenryIE/ba1b2b04f08e8dfba5bc6c8b76cfeee5 to your computer and use it in GitHub Desktop.
Save BrianHenryIE/ba1b2b04f08e8dfba5bc6c8b76cfeee5 to your computer and use it in GitHub Desktop.
<?php
/**
* @wordpress-plugin
* Plugin Name: Check Coupon Allowed Emails Earlier
* Description: Compares the billing email address to coupons' "Allowed Emails" restrictions anytime the checkout is updated.
* Plugin URI: https://github.com/woocommerce/woocommerce/issues/28560
* Version: 1.0.0
* Author: BrianHenryIE
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
* Text Domain: bh-wc-check-coupon-allowed-emails-earlier
* Domain Path: /languages
*/
/**
* @see WC_AJAX::update_order_review()
*
* @param string $posted_data_string Unparsed, unslashed posted data.
*/
add_action( 'woocommerce_checkout_update_order_review', function ( string $posted_data_string ) {
if( 1 !== preg_match('/billing_email=([^&]*)/', $posted_data_string, $output_array) ) {
return;
}
$billing_email = urldecode($output_array[1]);
if( ! is_email( $billing_email ) ) {
return;
}
$coupon_codes = WC()->cart->get_applied_coupons();
foreach( $coupon_codes as $coupon_code ) {
$coupon_id = wc_get_coupon_id_by_code( $coupon_code );
if( 0 === $coupon_id ) {
continue;
}
$coupon = new WC_Coupon( $coupon_id );
$email_restrictions = $coupon->get_email_restrictions();
if( empty( $email_restrictions ) ){
continue;
}
if( ! in_array( $billing_email, $coupon->get_email_restrictions(), true ) ) {
WC()->cart->remove_coupon( $coupon_code );
wc_add_notice("Coupon \"<em>$coupon_code</em>\" not valid for this email address", 'error' );
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment