2

Recently I've had an influx of spam users registering on my Wordpress website and I am trying to delete them all if:

  • they have a "Customer" role
  • haven't placed at least one order before

As I could not find a suitable plugin for this, I imagine an SQL query would be the fast options. Can anyone please help with what should I query to ensure I delete only Customers and not admins that haven't placed an order before.

1

1 Answer 1

0

There is a simple way to do it. Just create a php file and place it in your wordpress installation folder and then access that file. Once you accessed it through browser it will delete all spam user. Before your run that script, take a full bkup of your database so that in case of failure you don't lose any data. Put below code in that file

<?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;

$i = 0; /*counter starts at 0 not 1*/

/*log start time*/
$start_time = microtime(true);

/*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);
            /*stops at 1000th record - change this if you want*/
            if ($i++ == 999) {
                /*log the time it took*/
                $end_time = microtime(true);
                break;
            }
        }
    }
}
if (!$end_time) {
    $end_time = microtime(true);
}
$execution_time = ($end_time - $start_time);

echo "DONE! Deleted " . $i . " users.<br>";
echo "The time in " . date_default_timezone_get() . " is " . date("H:i:s");
echo " Execution time of script = " . $execution_time . " sec";

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.