Skip to content

Instantly share code, notes, and snippets.

@stevenkword
Last active August 29, 2015 14:02
Show Gist options
  • Save stevenkword/93af1d380121509dacb3 to your computer and use it in GitHub Desktop.
Save stevenkword/93af1d380121509dacb3 to your computer and use it in GitHub Desktop.
<?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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment