4

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.

8

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 );
  • What is the difference between "registration_errors" filter and "register_post" action? – Jalali Shakib Apr 9 '18 at 6:37
  • The register_post action lets you trigger other functionality before the user is created. The registration_errors filter lets you inject an "error" into the functionality and short-circuit the registration action entirely. – EAMann Apr 9 '18 at 14:00
0

This depends if you are building your own custom registration form where you implement the actual user registration or if you are using the registration form provided by WordPress.

If you are using the former, there aren't any since you'll have access to the POST data and be the one responsible for calling wp_insert_user() or wp_create_user() and making sure all the required info is correct i.e. username, email..

For the latter case, hook into register_post action. This is found in wp-login.php inside register_new_user() function.

/**
 * Code snippet...
 */
 } elseif ( email_exists( $user_email ) ) {
    $errors->add( 'email_exists', __( '<strong>ERROR</strong>: This email is already registered, please choose another one.' ) );
}

do_action( 'register_post', $sanitized_user_login, $user_email, $errors );

$errors = apply_filters( 'registration_errors', $errors, $sanitized_user_login, $user_email );

/** rest of the code after... **/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.