'username_exists' still returns an ID even after deleting record from the database?

Is there some kind of MySQL query cache turned on by default or something? I am trying to work on a user import script and I am seeing some strange results from the username_existsfunction after I delete records from the wp_users table. After I delete the records when I call username_exists WordPress is still returning the ID for the deleted user instead of false. Odd. What am I missing?

Solutions Collecting From Web of "'username_exists' still returns an ID even after deleting record from the database?"

By default, WordPress uses $wp_object_cache which is an instance of WP_Object_Cache to save on trips to the database.

Trace back username_exists() function, you will notice that get_user_by() uses WP_User::get_data_by() which return user data from $wp_object_cache immediately without checking if that user exists in database. Note that $wp_object_cache is stored in memory.

It means that if you deleted an user record directly in your database without cleaning up user cache, user data is still available. That’s the problem.

So what you’re missing?

  1. Missing to delete user the right way.

  2. Missing to clean user cache.

Caching can be anywhere, starting with request caching on mysql components side (unlikely to impact in this case), and object caching on wordpress side.

You are probably doing something wrong in your code, but it is always better to use the API (or wordpress admin as a front end to it) to delete things then to try to delete them by directly accessing the DB. It is not only caching that might give you problems but also user meta and other configuration settings that you are not going to take into account.