How to change role of all users with a specific role to another role?

Use the following function:

function wpse_replace_user_role( $from, $to ) {
    $args = array( 'role' => $from );
    $users = new WP_User_Query( $args );
    if ( !empty( $users->get_results() ) ) {
        foreach( $users->get_results() as $user ) {
            $u = new WP_User( $user->ID );
            $u->remove_role( $from );
            $u->add_role( $to );
            unset( $u );
        }
        unset( $users );
    }
}
  • $from – query all users with this role
  • $to – role to be set
    instead, for each queried user

Leave a Comment