Adil Elsaeed

Senior WordPress Developer

IT Consultant

Freelancer

Adil Elsaeed

Senior WordPress Developer

IT Consultant

Freelancer

Blog Post

Edit Username When User Registered on WordPress

19 September,2022 Snippets, WordPress

This is one of the tasks which I asked for in the last week and I want to share my solution with you.

We want to edit username when the user registered on WordPress based on his first and last name, the username will be generated from first and last name of the user, but you can adapt this code to make any other modification for username based on your needs.

This code will work for frontend user registeration and also when the user added by admin using dashboard.

add_filter('wp_pre_insert_user_data','adil_edit_username', 4, 10);
function adil_edit_username($data, $update, $user_id, $userdata ){
  // we only need to modify username on the registeration not on user update so
  if($update){
    return $data;
  }  
  $username = $userdata['first_name'].'-'.$userdata['last_name'];
  $data['user_login'] = strtolower($username); 
  return $data;
}

You notice that we use ‘wp_pre_insert_user_data‘ filter to hook on user data before it saved to database, and then geting the user first name and last name from the $userdata variable which bassed by the filter, then compine and lower case first and last name, and finaly modifiy $data[‘user_login’] which is the username, and this modify the username before it saved to database.

I hope you find this useful.

Open chat
1
Hellođź‘‹
Can I help you?