Auto-Update WordPress Username If Email Changes


About The Author
Avatar Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







Auto-Update WordPress Username If Email Changes

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.

Enjoy!


Share Your Thoughts

Leave a Reply

Your email address will not be published. Required fields are marked *


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!