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?
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?
3 Answers
Reset to default 16The 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.
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.
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