10

I want to create an Autocomplete function in WordPress. I want a search field from where username can be searched. I am using following JQuery UI.

<label>Users</label>

<input type="text" name="user_name" id="user-name" />

<?php

$get_arr_user = array('John', 'Rogers', 'Paul', 'Amanda', 'Peter');

?>

<script>

jQuery(document).ready(function($) {                                
var availableTags = <?php echo json_encode($get_arr_user); ?>;
$( "#user-name" ).autocomplete({
source: availableTags
});
});

</script>

My problem is that I am not able to get the list of Usernames in this format - array('John', 'Rogers', 'Paul', 'Amanda', 'Peter'); How do I get that?

15

The other answers are correct, but it's possible to achive the same thing with less code using wp_list_pluck():

$users = get_users();
$user_names = wp_list_pluck( $users, 'display_name' );

wp_list_pluck() used that way will get the display_name field of all the users in an array without needing to do a loop.

  • 2
    +1. Also, if less code is the target, then why not: $user_names = wp_list_pluck( get_users(), 'display_name' ); ;) – Fayaz Jul 12 '18 at 11:18
  • 1
    Yes that would work. I just separated them for clarity and consistency with the other answers I was referencing. Though I'd probably leave them separate in my own code, I'm not fond of using functions as arguments. – Jacob Peattie Jul 12 '18 at 11:21
3

Look at get_users() function.

<?php

$users = get_users();

foreach( $users as $user ) {
    // get user names from the object and add them to the array
    $get_arr_user[] = $user->display_name;
}

And you'll get the array similar to following:

Array
(
    [0] => John Doe
    [1] => Jane Doe
    [2] => Baby Doe
)

I'm pretty sure you'll want to exclude admins, order names and so on. So, look at the documentation to find out more get_users() arguments.

3

The get_users function will give you an array of user objects, from which you can extract an array of user names. Like this:

$args = array(); // define in case you want not all users but a selection
$users = get_users( $args );
$user_names = array();
foreach ( $users as $user ) {
    $user_names[] = $user->user_login;
}

Now $user_names is an array with login names. You can, off course, also use user_nicename, last_name, or whatever info is available in the wp_user object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.