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
$username
stringrequired- The username to check for existence.
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. |
Example
Use
username_exists()
in your scripts to decide whether the given username exists.Example
This function first checks username exist and if not exist, create user.
wp_insert_user()
checks if the username exists (by usingusername_exists()
), so this would be redundant (and potentially costly).