Home > Net >  Automatically set username as "first_name-last_name" with incremental number if duplicate
Automatically set username as "first_name-last_name" with incremental number if duplicate

Time:11-05

I have created a registration form on wordpress using Elementor Essential Addons.

There is no "username" field in the registration form, as I would like users to login with an email address and password (they never see the actual username outside of a pre-defined url structure).

So I have set the username to automatically generate as 'first_name.'-'.last_name" in the background. This works great with the following code:

add_filter( 'pre_user_login', 'name_as_username' );
function name_as_username( $user_login ) {

if(isset($_POST['first_name'])) $first_name = $_POST['first_name'];
if(isset($_POST['last_name'])) $last_name = $_POST['last_name'];

{
    $user_login = $_POST['first_name'].'-'.$_POST['last_name'];

return $user_login;
}
}

What I am struggling with is adding an incremental number at the end of the username if it already exists in my Wordpress database.

In other words, if "John-Doe" already exists, then automatically set the username to "John-Doe1". If "John-Doe1" already exists then automatically set the username to "John-Doe2" and so forth.

I have had a look at multiple other threads, but I can't seem to get any of the solutions to work:

How do I put extra number at the end of username if duplicate

Adding a number to MySQL Value If Found in DB

Below is the last full code snippet I have tried to get to work. Any help would be greatly appreciated!

add_filter( 'pre_user_login', 'name_as_username' );
function name_as_username( $user_login ) {

if(isset($_POST['first_name'])) $first_name = $_POST['first_name'];
if(isset($_POST['last_name'])) $last_name = $_POST['last_name'];

{
    $user_login = $_POST['first_name'].'-'.$_POST['last_name'];

return $user_login;

$i = 0;

    do {
    //Check in the database here
    $exists = exists_in_database($user_login);
    if($exists) {
        $i  ;
        $user_login = $user_login . $i;
    }
}   
    while($exists);
    //save $username
}
}

CodePudding user response:

You're very close. You need to use the WordPress function get_user_by() to look up the login you want to check. It returns false if it doesn't find the user.

Code like this will do it.

...
$original_login = $user_login;
do {
    //Check in the database here
    $exists = get_user_by( 'login', $user_login ) !== false;
    if($exists) {
        $i  ;
        $user_login = $original_login . $i;
    }
}  while($exists);

It's certainly possible to add your own tables to WordPress, but you need to do so in a plugin or theme; they have activation and deactivation hooks allowing you to create and drop the tables. For the purpose in your question, it's not the slightest bit necessary nor helpful.

  • Related