Restrict WordPress Registration to Email Whitelist

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.

3 Comments

  1. The Frosty says…

    I like this one!

  2. 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:

    is_email("bob.o\'neill@domain.com"); // false

    As opposed to:

    is_email("bob.o'neill@domain.com"); // true

    And you get a core registration error.

  3. Jordan says…

    Thank you, this was exactly what I needed!

RSS feed for comments on this post. TrackBack URL

Leave a Comment

October 11, 2011

Filed in Development, Wordpress

There are 3 comments »


« Back to the Blog