函数文档

username_exists()

💡 云策文档标注

概述

username_exists() 函数用于检查指定用户名是否已存在于 WordPress 数据库中,返回用户 ID 或 false。它是用户管理中的核心函数,常用于注册、编辑用户等场景。

关键要点

  • 函数接受一个字符串参数 $username,用于检查用户名是否存在
  • 返回值为 int|false:存在时返回用户 ID,不存在时返回 false
  • 内部使用 get_user_by('login', $username) 实现用户查找
  • 提供 'username_exists' 过滤器钩子,允许开发者自定义检查逻辑
  • 与 wp_insert_user() 等函数配合使用,避免重复检查

代码示例

$username = sanitize_user( $_POST['username'] );
if ( username_exists( $username ) ) {
    echo "Username In Use!";
} else {
    echo "Username Not In Use!";
}

注意事项

  • wp_insert_user() 内部已调用 username_exists(),重复使用可能增加性能开销
  • 建议先对输入的用户名进行 sanitize_user() 处理以确保安全

📄 原文内容

Determines whether the given username exists.

Description

For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.

Parameters

$usernamestringrequired
The username to check for existence.

Return

int|false The user ID on success, false on failure.

Source

function username_exists( $username ) {
	$user = get_user_by( 'login', $username );
	if ( $user ) {
		$user_id = $user->ID;
	} else {
		$user_id = false;
	}

	/**
	 * Filters whether the given username exists.
	 *
	 * @since 4.9.0
	 *
	 * @param int|false $user_id  The user ID associated with the username,
	 *                            or false if the username does not exist.
	 * @param string    $username The username to check for existence.
	 */
	return apply_filters( 'username_exists', $user_id, $username );
}

Hooks

apply_filters( ‘username_exists’, int|false $user_id, string $username )

Filters whether the given username exists.

Changelog

Version Description
2.0.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Example
    This function first checks username exist and if not exist, create user.

    function wpdocs_get_user_id( $username ) {
    	$user_id = username_exists( $username );
    
    	if ( ! $user_id ) {
    		$userdata = array(
    			'user_login' => $username,
    			'user_pass'  => null,
    		);
    
    		$user_id = wp_insert_user( $userdata );
    	}
    
    	return $user_id;
    }