Auto-Update WordPress Username If Email Changes

Aug 19, 2019

Auto-Update WordPress Username If Email Changes


This post was originally created on our sister site WP Cover.
View Original Article
August 19, 2019

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!

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

Additional News

Perfect!

Let's get started. Fill out the form below to email us or request a call back.


FREE: 10 Step Guide To Choosing A Web Design Company

FREE: 10 Step Guide To Choosing A Web Design Company

Download your free e-book. Learn the questions you should be asking prior to partnering with a web design company. Enter your email address and we'll send it to you right away!

We've sent the e-book to your email address!