Prevent User Registration From Specific Domain in WordPress
  • LET'S TALK!

    Fill in the form below to make an enquiry or find my contact details on my contact page.

  • This field is for validation purposes and should be left unchanged.

Freelance WordPress Developer

Prevent User Registration From Specific Domain in WordPress

Normally it is a good idea to disable user registration  if you are not planning to use membership feature because could lead spammers can attack your website with spam user registrations.

I used registration_errors hook in WordPress which filters the errors encountered when a new user is being registered. If any errors are present, WordPress will abort the user’s registration. This filter can also be used to create custom validation rules on user registration. This hook fires when the form is submitted but before user information is saved to the database. So I created a custom rule to check the user’s email domain and provide an error if user’s email match blacklisted domain.

Here is the function you can dump in your theme’s functions.php file. The following function will prevent user registration if WordPress find “domain.Com” in user’s email address.

 

// prevent user registration from specific domain
function ns_disable_email_domain ( $errors, $sanitized_user_login, $user_email ) {
   list( $email_user, $email_domain ) = explode( '@', $user_email );
   if ( $email_domain == 'domain.com' ) {
     $errors->add( 'email_error', __( '<strong>ERROR</strong>: Domain not allowed.', 'my_domain' ) );
   }
   return $errors;
}
add_filter( 'registration_errors', 'ns_disable_email_domain', 10, 3 );

Thank you for seeing my code snippet and feel free to share and comment :).Do you have any interesting changes to this snippet that you know or some other cool code snippets that you’d like to share? Let everyone know in the comments what cool tricks you’ve come up with or you can let me know by contacting me (here)

ABOUT AUTHOR

Nuno

Hi, I'm a Freelance Web Developer and WordPress Expert based in London with a wealth of website development and support experience. I am great at problem solving and developing quick solutions.