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!";