I am using Woocommerce and am trying to modify the function that checks if an email is a duplicate. Instead of what usually happens I want this to happen...
- Somebody tries to register with an existing email address
- Woocommerce detects that this is a duplicate
- Woocommerce automatically assigns it a random email address instead
I can achieve this easily by changing the following in wc-user-functions.php..
if ( email_exists( $email ) ) {
return new WP_Error( 'registration-error', __( 'An account is already registered with your email address. Please login.', 'woocommerce' ) );
}
to....
if ( email_exists( $email ) ) {
$length = 5;
$randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
$email = ''. $randomString . '@example.com';
}
Now what I need to do is create this same functionality but using a hook or filter so it can safely be run from my child themes functions.php file instead of hacking the core.
Can anyone help?
Dbranes answers:
The <em>email_exists()</em> WordPress core function uses the pluggable <em>get_user_by()</em> function.
You could then override it with your own version that returns <em>false</em> if the email exists within the Woo context, with your own filter for example. You could also modify the email within the <em>WP_User</em> object returned from that function.
Then you could additionally use the <em>woocommerce_new_customer_data</em> filter if you need to.
<strong>Example:</strong>
Here's an untested example to put into your <em>functions.php</em> file:
/**
* Override the pluggable get_user_by function.
*/
function get_user_by( $field, $value ) {
$userdata = WP_User::get_data_by( $field, $value );
if ( !$userdata ) {
return false;
}
$user = new WP_User;
$user->init( $userdata );
// We only add this line:
$user = apply_filters( 'wpq_get_user_by', $user, $field, $value );
return $user;
}
/**
* Allow duplicate emails in Woo registration
*/
add_filter( 'woocommerce_process_registration_errors', 'wpq_woocommerce_process_registration_errors' );
function wpq_woocommerce_process_registration_errors( $validation_error ) {
add_filter( 'wpq_get_user_by','wpq_get_user_by', 10, 3 );
return $validation_error;
}
function wpq_get_user_by( $user, $field, $value ) {
if( 'email' === $field ) {
$user = false;
add_filter( 'woocommerce_new_customer_data', 'wpq_woocommerce_new_customer_data' );
}
return $user;
}
function wpq_woocommerce_new_customer_data( $userdata ){
$userdata['email'] = uniqid( 'fake_', true ) . '@example.com';
return $userdata;
}