Can I hook into user registration *before* a user is created?

I want to limit registration based on the domain associated with their email address. I was looking at the user_register action hook, but it fires after the user is already inserted, which, although it could be hacked into working, is less than ideal. I want to preempt rather than retroactively remove invalid users.

I’ve looked through the source in wp-includes/user.php, but nothing in there looks to be helpful. I did notice the pre_user_email filter, but that doesn’t seem to offer any options for doing anything useful since I can’t see a way to do anything with that.

2 s
2

You’re looking in the wrong place.

When a user first attempts to register, their username and email is processed and sanitized inside the register_new_user() function in wp-login.php. This is where you want to do your filtering.

Before the user is created, WordPress will pass the sanitized user login, email address, and an array or errors through the ‘register_post’ action. If there are any errors after that, then the user is not added and they will see the errors in the UI.

So the following untested function might help:

function prevent_email_domain( $user_login, $user_email, $errors ) {
    if ( strpos( $user_email, '@baddomain.com' ) != -1 ) {
        $errors->add( 'bad_email_domain', '<strong>ERROR</strong>: This email domain is not allowed.' );
    }
}
add_action( 'register_post', 'prevent_email_domain', 10, 3 );

Leave a Comment