My custom code in my custom (class-based) plugin for some reason, writes the same record twice, when as you can see it's called once. This double write also happens even when I do the same type of insert into the wp_posts table, so it's not specific to the wp_users table. I'm baffled. Any ideas appreciated.

class InsertUserWP {

    function dbase_insert_wp_user() {
        global $wpdb;

        $wp_users_table = $wpdb->prefix . 'users';

        $newUser = $wpdb->insert(
                'user_login' => 'deleteme_login_' . rand(1, 10000),
                'user_pass' => md5('deletemmepass'),
                'user_nicename' => 'deleteme_nicename',
                'user_email' => 'mario' . rand(1, 10000) . '@email.com',
                'user_status' => 0
        echo 'new user ID is: ' . $wpdb->insert_id . '<br>'; // (returns the first ID on screen)

    // call the above insert function
    function dbase_call_user_insert() {

// Run the insert
$insertCompanies = new InsertUserWP(); //instantiate the class
$insertCompanies->dbase_call_user_insert(); // run the insert function within
  • Depending on where your code is inserted, it might be running multiple times over the request lifecycle. You need to first check if the user exists before inserting, but as you're using a random number, and users are unique by user_login and WP checks if the email is in use, it is seeing them as different users.
    – Paul
    Oct 4 at 10:55
  • Where this is located is super important as Paul said, if you've dumped this inside a functions.php then a user is going to be created on every request, not page load, request. That means every AJAX request, every page load, every admin request, REST API request, cron jobs, even assets that you're running through PHP plugins would insert a user. As an aside, this could be dramatically simplified to just the dbase_insert_wp_user function with the removal of the class, there's no object oriented programming here and no local state to store on the object so there's no reason for a class
    – Tom J Nowell
    Oct 4 at 11:05
  • You guys are definitely onto something here - thank you. It seems I don't have enough control over when the class/functions are fired, so my plugin fires with every browser refresh. I'll need to check my main plugin file and think of "if" condition to stop duplicate run of my script. It can even cause it to write to DB more than twice, I noticed after, depending on what is firing (core functionality) on the site.
    – Mario
    Oct 4 at 15:59


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.