There may be times where you want to clean up your WordPress database of WooCommerce customers. For example if your website is the unfortunate target of a spam attack where hundreds, or maybe thousands, of spam user accounts get created. You probably don't want to go to your users page and have 95% of the users be spam users.

The code below can be run to clean up those users. Just create a PHP file in the root of your WordPress directory and put this code there. I usually call it something like prune_customers.php.

prune_customers.php

<?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 until all users have been deleted
set_time_limit(0);

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

// ignore user registered in the past x days
$days_since_registration = 30;

// loop through all users
foreach($wpdb->get_results('SELECT ID from '.$wpdb->prefix.'users WHERE DATEDIFF(NOW(),user_registered) > '.$days_since_registration.' ORDER BY ID DESC') as $user) {
    
  // get user object
  $user = get_user_by('ID', $user->ID);

  $roles = $user->roles;

  // only run for customers
  if ($roles[0] === "customer") {

    // check the number of orders and delete user if it's 0
    $order_count = wc_get_customer_order_count( $user->ID);
    if ($order_count === 0) {
        wp_delete_user($user->ID);
        echo "DELETE {$user->user_login}: {$order_count} \n";
    } else {
        echo "{$user->user_login}: {$order_count} \n";
    }
  }
}

echo "DONE!";

Then you can run the code from your browser or from the command line. I will usually execute the PHP file from the command line by making sure I'm in the same directory as the file I just created and running the following.

bash

# make sure you're in the correct directory
cd path/to/directory

# execute php file
php prune_customers.php

If you would rather run the code in the browser you can visit https://yourwebsite.com/ prune_customers.php (or whatever name you gave your file). This will run the code in that file. Running the code this way may result in your browser timing out, depending on how many users there are that need deleted.

Once you finish deleting all the users I would make sure to delete this file to make sure it doesn't get run by accident later on.

Was this post helpful?