Mass delete spam accounts

Yes. There are a variety of ways to do this, primarily, we’ll need to tackle the wp_delete_user() function.

Your first task, and the tricky one, is to identity which accounts are spam, and which are real. This can be quite an adventure if your site gains new users regularly.

With the following example, we target two values, the user’s email account and meta_data.

In this case, we have an idea if it’s a spam account by interpreting the email address. So let’s add a list in an array:

$emails = array(
    '[email protected]',
    '[email protected]',
    '[email protected]',
);

Then we have a custom user meta data named points:

$meta_key = 'points';

And in our case, we know that if the meta key value is 10, then it is definitely a spam user. So we set the value:

$meta_key = 10;

Now let’s put it together into a function:

function wpse_delete_users_by_email($emails, $meta_key, $meta_value) {

    if (!is_array($emails)) return;

    foreach ($emails as $email) {

        // get user data via email
        $user = get_user_by( 'email', $email );
        $user_id = $user->ID;
        $user_email = $user->user_email;

        // get
        $meta_data = get_user_meta($user_id, $meta_key, TRUE);

        // if meta data equals the meta value
        if ($meta_data == $meta_value) {

            // confirm that emails match
            if ($user_email == $email) {

                // must include this, or it will throw a 'call to undefined function' error
                require_once(ABSPATH.'wp-admin/includes/user.php' );

                // delete spam user
                wp_delete_user( $user_id );

                // display results
                echo '<br>' . $email;

            }

        }

    }

}

Simple stuff, but sometimes when dealing with spam and bots, one less headache can be valuable.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)