Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate a unique username in WordPress
<?php
/**
* Recursive function to generate a unique username.
*
* If the username already exists, will add a numerical suffix which will increase until a unique username is found.
*
* @param string $username
*
* @return string The unique username.
*/
function generate_unique_username( $username ) {
static $i;
if ( null === $i ) {
$i = 1;
} else {
$i++;
}
if ( ! username_exists( $username ) ) {
return $username;
}
$new_username = sprintf( '%s-%s', $username, $i );
if ( ! username_exists( $new_username ) ) {
return $new_username;
} else {
return call_user_func( __FUNCTION__, $username );
}
}
@marounmelhem

This comment has been minimized.

Copy link

marounmelhem commented Apr 30, 2018

Perfect thank you! I also added sanitize_title to remove spacing/extra characters:

function generate_unique_username( $username ) {

	$username = sanitize_title( $username );

	static $i;
	if ( null === $i ) {
		$i = 1;
	} else {
		$i ++;
	}
	if ( ! username_exists( $username ) ) {
		return $username;
	}
	$new_username = sprintf( '%s-%s', $username, $i );
	if ( ! username_exists( $new_username ) ) {
		return $new_username;
	} else {
		return call_user_func( __FUNCTION__, $username );
	}
}
@rianrismawati

This comment has been minimized.

Copy link

rianrismawati commented Dec 12, 2018

Where can I put this code?

I really need help, thankyou

@KiwiKilian

This comment has been minimized.

Copy link

KiwiKilian commented May 20, 2019

@marounmelhem You may want to use sanitize_user( $username ) instead of sanitize_title( $username ).

@brian-stinar

This comment has been minimized.

Copy link

brian-stinar commented May 27, 2019

My final, minor improvement on making sprintf more explicit and including @KiwiKilian 's suggestion.

function generate_unique_username( $username ) {

	$username = sanitize_user( $username );

	static $i;
	if ( null === $i ) {
		$i = 1;
	} else {
		$i ++;
	}
	if ( ! username_exists( $username ) ) {
		return $username;
	}
	$new_username = sprintf( '%s-%s', $username, $i );
	if ( ! username_exists( $new_username ) ) {
		return $new_username;
	} else {
		return call_user_func( __FUNCTION__, $username );
	}
}

Nice approach @philipnewcomer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.