Today I ran into a request with a client that I wanted to document and share: restricting registration to a WordPress site to a whitelist of email address domains.
Luckily, there’s a sweet hook, registration_errors
you can get into. It accepts 3 parameters: $errors
, which is the WP_Error object; $login
, which is the user_login
entered during registration; and $email
, which is the user_email
entered during registration.
Here’s the code:
add_action('registration_errors', 'sizeable_restrict_domains', 10, 3);
function sizeable_restrict_domains( $errors, $login, $email ) {
$whitelist = array('sizeableinteractive.com', 'theandystratton.com');
if ( is_email($email) ) {
$parts = explode('@', $email);
$domain = $parts[count($parts)-1];
if ( !in_array(strtolower($domain), $whitelist) ) {
$errors->add('email_domain', __('ERROR: You may only register with an approved email address.'));
}
}
return $errors;
}
Remember to specify some kind of priority AND how many parameters your callback function will accept when adding actions. I always forget to specify them when coding quickly from scratch and wonder why I’m getting weird values in my callback functions parameters.
Happy WP’ing.
RSS feed for comments on this post. TrackBack URL
The Frosty says…
I like this one!
andy says…
Thanks, during this project I found a bug of sorts in registration, I need to report and submit patch, hopefully it gets included in core. RFC allows apostrophes in email address usernames.
If you register with bob.o’neill@domain.com, the
is_email()
function is processed on the submitted email address, which should be valid.With WP escaping form data, it’s running:
As opposed to:
And you get a core registration error.
Jordan says…
Thank you, this was exactly what I needed!
Don B Mason says…
In this example your whitelist is explicitly defined inside the code itself. could this be extended to pull from a DB or Excel sheet?
(newbie here)
Thanks
Andy says…
Yes, you could use whatever code you needed to get the array or modify this code as needed to make it work. If you added your own code to set $whitelist to an array of domains, the same code would work (just set the $whitelist variable to a single dimensional array of domains before the rest of the code runs.