Categories
Code WordPress

Use Wildcards with WP_User_Query to Search for WordPress Users

Information about how to use the wildcard user search in WP to properly populate things like JSON arrays for use with autocomplete JS.

WP_User_Query()

<?php
/**
* Search for users by name and return a JSON object of matches
*
* An example method that demonstrates how to use wildcards (*'s) when
* looking up users. This particular example would be used to create
* a new endpoint that would output a JSON array of returned users.
* Something like this would be useful for JS autocomplete queries.
*/
function skw_user_autocomplete( $search_term ) {
// Note the astrisks
$user_query = new WP_User_Query( array(
'search' => '*' . $search_term . '*',
) );
// Get the results from the query, returning the first user
$users = $user_query->get_results();
$user_ids = array();
foreach( $users as $user ) {
$user_ids[] = array(
'ID' => $user->data->ID,
'label' => $user->data->user_login,
'display_name' => $user->data->display_name
);
}
header( 'Content-Type: application/x-json' );
echo $json = json_encode( $user_ids );
die;
}

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.