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
Leave a Reply