Prevent wp_insert_user from creating duplicate users

I have a custom plugin that automatically creates a new user via wp_insert_user() if the current user does not exist yet.

We use data from our remote ldap server to provide the new user’s details (user_login, user_email, etc.) for the wp_insert_user() function call.

This works without a hitch on most of our sites, but on a site that uses WP REST API to render the page, we have noticed that we are sometimes getting duplicate users in the database, same login name, email, etc. As far as I can tell, this shouldn’t happen with wp_insert_user().

I am guessing that multiple async requests on the same page are triggering the wp_insert_user() function at virtually the same moment so that WordPress is not able to catch the duplicate entry before it is inserted. Is that possible? If so, would there be a way to always prevent duplicate inserts that resolve asynchronously?

0

Leave a Comment