I have created a website on WordPress where users can register and add various information about themselves. The site has been put together using Elementor, with the WPEverest User Registration form governing the user registration on the front-end.
On registration, I would like to force the username of the new user to be first_name-last_name (I am capturing the fields in the registration form).
But here's the catch: I need to check the existing usernames to ensure there are no usernames that match the new registration. If there are, I would like to append an integer (in sequence) onto the username to differentiate it.
So in other words:
- The first John Smith registers and is assigned a username john-smith;
- The second John Smith registers and is assigned the username john-smith-2;
- The third John Smith registers and is assigned the username john-smith-3;
I have added the below code, which works on registration, but it also fires when I update a user in the back-end. So if I update the first John Smith, he becomes john-smith-2; stranger, if I update him again he becomes john-smith-2-2.
I would like this to fire on registration only.
Any help would be very much appreciated, thanks!
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'];
$original_login = $user_login;
$i = 1;
do {
//Check in the database here
$exists = get_user_by( 'login', $user_login ) !== false;
if($exists) {
$i++;
$user_login = $original_login .'-'. $i;
}
} while($exists);
}
return $user_login;
}