How to delete users with no order history through phpmyadmin sql?

Hector’s answer works well, but if you have have a large number of users you need to remove (in my case, it was over 13,000 spam registrations) I find using this little utility script works wonders, and doesn’t require you to manually check and delete from the user-list in the admin panel.

The script still might time out, so keep an eye on it if you are clearing out a lot of users.

cleanusers.php

//Load WP functions and DB access
include('wp-load.php');

//required for wp_user_delete
require_once( ABSPATH.'wp-admin/includes/user.php' );

//Let it run forever
set_time_limit(0);

//Get the $wpdb database object
global $wpdb;


//Loop through all users
foreach($wpdb->get_results('SELECT ID from '.$wpdb->prefix.'users ORDER BY ID DESC') as $user) {


    //Get user object
    $user = get_user_by('ID', $user->ID);

    //Check if this user's role (customer, subscriber, author, etc.)
    $roles = $user->roles;
    if ($roles[0] == "customer") {

        //Check the order count and delete if it is 0
        $order_count = wc_get_customer_order_count( $user->ID);
        if ($order_count === 0) wp_delete_user($user->ID);

    }

}

echo "DONE!";

Place the above file in your installation folder, then access via browser or run via command-line.

Cheers,
C.

Leave a Comment

tech