username_exists( string $username ): int|false

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

VersionDescription
2.0.0Introduced.

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

You must log in before being able to contribute a note or feedback.