Prevent User Registration From Specific Domain in WordPress

Normally it is  a good idea to disable user registration  if you are not planing 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 custom rule to check user’s email domain and provide 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 fell 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 contact me (here)

ABOUT AUTHOR

Nuno

I am 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.

  • LET'S TALK!

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

  • This form collects your name and email address so that I can respond to the enquiry(ies) that you submit via this website. Please check my privacy policy for the full story on how I use, protect and manage your submitted data.