Allow WordPress users to change username


Ever since I have started working with WordPress, I always had a burning question inside, to know why WordPress does not allow editing or changing username once set while registering. Recently when I had a requirement in a project to do so, I looked more into it and found that I am not the only one with that question. There is an open ticket in WordPress with more or less a similar feature request.

There has been a lot of discussion about why and why not this feature to be entertained. While the community is still having the discussion, I had a go into this and made it work for my client, who is very happy with this feature.

In my project, the user has the ability to maintain its profile in the front end and hence also has the ability to change the user name. I will here share the piece of relevant code which needed to be used to make this work.

Here I first sanitized the post value for a username and checked the requested username with the present username of the logged in user, and also if a similar username exists for others or not. If it passes all this, we run the SQL query to change the username for the current user.

I have another variable $uname in the snippet, which by default is set to 0 and changed to 1 when the username is changed. I have done this to keep a tab when the username is changed, because WordPress logs out the user the next instance when the username is changed, and if not taken care of gives a bad user experience.

To know more on why this happens, you can read this blog on WordPress auth cookies, which explains how an username is used as an auth cookie and hence changing the username logs out the user.

To take care of this, you can re login the user once this username is changed using wp set auth cookie.

It perfectly worked for me as in my project, the user registered can only save few items and gets the added privilege of accessing some of the pages/posts which they cannot otherwise. Hope this works for you too!!

Do write your comments below and let me know if this works or did not work for you.


Maruti Mohanty

I am a happy go lucky WordPress Developer, who loves biking, movies and learning different languages


2 Responses

  1. Alex says:

    Where do I put the code above?

Leave a Reply

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

%d bloggers like this: