WordPress Snippet: Change user’s role by username or email address

Here is a sample PHP code snippet to change the role of multiple users in WordPress based on their username:

<?php
$usernames = ['username1', 'username2', ...]; // An array of the usernames of the users you want to change the role for
$new_role = 'new_role'; // The new role you want to assign to the users

foreach ($usernames as $username) {
    $user = get_user_by('login', $username);
    if (!empty($user)) {
        $user->set_role($new_role);
    }
}

Replace [username1, username2, ...] with the usernames of the users you want to change the role for and [new_role] with the new role you want to assign to the users.

If you want to select users by email address only change ‘login’ to ’email’ and the second parameter to an array of email addresses like this:

<?php
$emails = ['email1@example.com', 'email2@example.com', ...]; // An array of the usernames of the users you want to change the role for
$new_role = 'new_role'; // The new role you want to assign to the users

foreach ($emails as $email) {
    $user = get_user_by('email', $email);
    if (!empty($user)) {
        $user->set_role($new_role);
    }
}

The available roles in WordPress are administrator, editor, author, contributor, and subscriber.

As these snippets used to run only once, you can use something like Snippets plugin to save the snippet and select the run once option to avoid running multiple times on your WordPress installation.

Leave a Comment