Search code examples
phpwordpresswordpress-rest-api

Wordpress multisite - How to retrieve all user roles in each site in the network


I have a wordpress mutisite, and I have a duplicate user in two sites with two different roles, when I tried to costmize the return of wp/v2/users endpoint to return the users with the roles, what I got was an array with only one role.

This is how I get the roles:

 get_userdata($userId)->roles

And the response is:

"role": [
"author"
]

Does any one have an Idea how to retrieve all user roles in each site?


Solution

  • You need to iterate through multiple blogs:

    $roles = [];
    
    foreach (get_sites() as $blog){
        switch_to_blog($blog->blog_id);
        $roles = array_merge($roles, get_userdata($userId)->roles) 
    }
    
    restore_current_blog();