How to override WordPress registration and insert an auto-generated username?

I need to auto-generate usernames upon WordPress registration. I have a custom registration form set up and would like to create the username in functions.php.

Can someone tell me why this isn’t working? It seems like it should work after reading the WordPress Codex on customized registration forms?

function register_hook ( $user_id ) {
  update_user_meta( $user_id, 'signup_username', 'the-auto-generated-name' );
  // also tried this:
  // update_user_meta( $user_id, 'user_login', 'the-auto-generated-name' );
}
add_action( 'user_register', 'register_hook' );

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

One alternative is to modify the $_POST['user_login'] input value when submitting new registration form, that is before WP process the registration form. A good hook to achieve this is login_form_register that fires before processing and rendering registration form. login_init also works but need more work to make sure we are on register action.

add_action('login_form_register', 'custom_user_login');
function custom_user_login() {

    // make sure regisration form is submitted
    if ($_SERVER['REQUEST_METHOD'] != 'POST')
        return;

    // base of user_login, change it according to ur needs
    $ulogin = 'random-user';

    // make user_login unique so WP will not return error
    $check = username_exists($ulogin);
    if (!empty($check)) {
        $suffix = 2;
        while (!empty($check)) {
            $alt_ulogin = $ulogin . '-' . $suffix;
            $check = username_exists($alt_ulogin);
            $suffix++;
        }
        $ulogin = $alt_ulogin;
    }

    $_POST['user_login'] = $ulogin;
}

Method 2

You can alter user login via the pre_user_login filter. Note that this runs when the user is created or updated.

function wpd_custom_user_login( $user_login ) {
    $user_login = 'the-auto-generated-name';
    return $user_login;
}
add_filter( 'pre_user_login' , 'wpd_custom_user_login' );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x