I'm using the REST API to create/update/delete users on a multisite install in order to sync data with a 3rd party resource. When I am checking whether to update or create a user, I'm using the search
parameter to search on usernames, which works fine on a single site, but if a user exists in the system on a different site, how can I tell beyond trying the insert, which triggers a Username is already in use error? I've found this proposed change, which looks to be exactly what I need, but it hasn't made it into code yet. How can I achieve this? I don't mind writing a custom endpoint and doing it in PHP, but I can't find any functions that allows searching globally for users. Even WP_User_Query
appears limited to one blog at a time.
-
This is the closest solution I've found so far: wordpress.stackexchange.com/questions/127081/…– ken.dunningtonAug 29, 2017 at 20:08
1 Answer
It appears you can do this using a blog_id
of 0
:
$args = array( 'blog_id' => 0 );
$users = get_users( $args );
var_dump( $users );
If you want to search for a specific user, the process is similar:
$args = array( 'blog_id' => 0, 'search' => '{username to search for}' );
$users = get_users( $args );
var_dump( $users );
I discovered this while poking around in the wp-cli
source code (since I knew that wp user list --network
would return a list of all the users on a Multisite network). It's corroborated by a user comment on the WP_User_Query::prepare_query()
documentation.
-
Re-reading your question, I'm not sure this will help with REST API user searching on a remote WP installation.– Pat JAug 30, 2017 at 15:30
-
1Maybe not with the out-of-the-box REST API, but this seems like a cleaner way to handle the problem without resorting to WP_Query directly. This could be easily added via a custom endpoint in a simple plugin or
functions.php
so I'm going to mark it as the accepted answer. Sep 5, 2017 at 16:27