wp_ajax_autocomplete_user

函数
wp_ajax_autocomplete_user ( No parameters )

wp_ajax_autocomplete_user: 这个AJAX动作返回一个符合搜索查询的用户列表。它接收搜索查询作为一个参数。

用于用户自动完成的Ajax处理程序。

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 ) );
}

常见问题

FAQs
查看更多 >