Featured Image Auto-Update WordPress Username If Email Changes

Auto-Update WordPress Username If Email Changes

Cabe Nolan Author
Cabe Nolan August 19, 2019


This post was originally created on our sister site WP Cover.
View Original Article

We build out a lot of custom backends and applications on WordPress. A lot of these custom backends require a client or customer portal that they can login to and access content, manage their account, etc. as well as being able to register. When we build these out, we typically always force the username in WordPress to be the same as the user’s email address to keep things simple. However, the issue that comes up is what happens when a user or an admin must update somebodies email address? By default, WordPress does not allow usernames to be changed and the wp_update_user will ignore any changes to the username.

In order to keep username and email the same indefinitely, we needed to come up with a function to override WordPress preventing usernames from being updated. Here it is:


function wpcover_user_profile_update_email( $user_id, $old_user_data ) {
  $user = get_userdata( $user_id );
  if($old_user_data->user_email != $user->user_email) {
	  if ( !username_exists( $user->user_email ) ) {
	    wp_update_user( array ( 'ID' => $user->ID, 'user_nicename' => $user->user_email, 'nickname' => $user->user_email) ) ;
	    global $wpdb;
	    $wpdb->update($wpdb->users, array('user_login' => $user->user_email), array('ID' => $user->ID));
add_action( 'profile_update', 'wpcover_user_profile_update_email', 10, 2 );


I’ll explain the above code. First, we’re capturing the old user data so we can compare the old email to the new. If the old email does not match the new email, we’ll check and see if that username already exists since it must be unique. If it doesn’t exist, then we’ll update the email address as well as the username to match.

Once implemented, this code will fire both within wp-admin if an administrator updates an email as well as on a frontend ‘My Account’ type of set up so if the user updates their email we’ll match their username.


The post Auto-Update WordPress Username If Email Changes appeared first on WP Cover.


Cabe Nolan Author Image
Written by

Cabe Nolan