• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Solution / WP CLI Migrate User Roles

WP CLI Migrate User Roles

Last updated on December 17, 2020 by Sal Ferrarello

Recently on a project I wanted to migrate WordPress users with a certain role to a different role. This is the command I used.

General Formula

wp user list --role=<old role> --format=ids | xargs -d ' ' -I ID wp user set-role ID <new role>

Example

For all users with the role contributor, I wanted to change their role to subscriber. This is the command I used:

wp user list --role=contributor --format=ids | xargs -d ' ' -I ID wp user set-role ID subscriber

How it Works

List all Users with role “contributor”

wp user list --role=contributor --fields=ID,user_login,roles

+----+------------+-------------+
| ID | user_login | roles       |
+----+------------+-------------+
| 4  | c1         | contributor |
| 5  | c2         | contributor |
| 6  | c3         | contributor |
+----+------------+-------------+

We are going to use a slightly modified version of this query (using --format=ids) that returns only the user IDs (in this case 4 5 6).

wp user list --role=contributor --format=ids

Set User with a Specific ID to “subscriber” role

To change the role of a single user (e.g. user with ID 4) to subscriber

wp user set-role 4 subscriber

xargs

Since we need to replace 4 with each of the values returned by our query for all contributors, we are going to use xargs.

The command we pass into xargs is wp user set-role ID subscriber (where ID will be our variable).

We tell xargs that ID is our variable with -I ID

Since our original query returns the ID numbers separated by spaces (e.g. 4 5 6) we need to tell xargs to split the string at each blank space (by default xargs splits on newlines), we tell xargs to split on spaces with -d ' '

Solution

Putting these pieces together we get

wp user list --role=contributor --format=ids | xargs -d ' ' -I ID wp user set-role ID subscriber
Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit
Warning! This is a draft, not a finalized post. See full draft disclosure.

Filed Under: Draft, Solution Tagged With: WordPress, wp-cli

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in