wp_ajax_autocomplete_user() WordPress Function
The wp_ajax_autocomplete_user() function is used to search for a user via Ajax. It takes two parameters: the search term and the number of results to return. The function returns a JSON object containing the user ID, user login, user email, and user display name.
wp_ajax_autocomplete_user() #
Ajax handler for user autocomplete.
Source
File: wp-admin/includes/ajax-actions.php
function wp_ajax_autocomplete_user() { if ( ! is_multisite() || ! current_user_can( 'promote_users' ) || wp_is_large_network( 'users' ) ) { wp_die( -1 ); } /** This filter is documented in wp-admin/user-new.php */ if ( ! current_user_can( 'manage_network_users' ) && ! apply_filters( 'autocomplete_users_for_site_admins', false ) ) { wp_die( -1 ); } $return = array(); // Check the type of request. // Current allowed values are `add` and `search`. if ( isset( $_REQUEST['autocomplete_type'] ) && 'search' === $_REQUEST['autocomplete_type'] ) { $type = $_REQUEST['autocomplete_type']; } else { $type = 'add'; } // Check the desired field for value. // Current allowed values are `user_email` and `user_login`. if ( isset( $_REQUEST['autocomplete_field'] ) && 'user_email' === $_REQUEST['autocomplete_field'] ) { $field = $_REQUEST['autocomplete_field']; } else { $field = 'user_login'; } // Exclude current users of this blog. if ( isset( $_REQUEST['site_id'] ) ) { $id = absint( $_REQUEST['site_id'] ); } else { $id = get_current_blog_id(); } $include_blog_users = ( 'search' === $type ? get_users( array( 'blog_id' => $id, 'fields' => 'ID', ) ) : array() ); $exclude_blog_users = ( 'add' === $type ? get_users( array( 'blog_id' => $id, 'fields' => 'ID', ) ) : array() ); $users = get_users( array( 'blog_id' => false, 'search' => '*' . $_REQUEST['term'] . '*', 'include' => $include_blog_users, 'exclude' => $exclude_blog_users, 'search_columns' => array( 'user_login', 'user_nicename', 'user_email' ), ) ); foreach ( $users as $user ) { $return[] = array( /* translators: 1: User login, 2: User email address. */ 'label' => sprintf( _x( '%1$s (%2$s)', 'user autocomplete result' ), $user->user_login, $user->user_email ), 'value' => $user->$field, ); } wp_die( wp_json_encode( $return ) ); }
Expand full source codeCollapse full source codeView on TracView on GitHub
Changelog
Version | Description |
---|---|
3.4.0 | Introduced. |