WordPress at Your Fingertips

wp_generate_password()WP 2.5.0

Generates a random password. You can specify the length and what characters to use.

Uses wp_rand() to create passwords with far less predictability than similar native PHP functions like rand() or mt_rand().

Pluggable function — this function can be replaced from a plugin. It means that this function is defined (works) only after all plugins are loaded (included), but before this moment this function has not defined. Therefore, you cannot call this and all functions depended on this function directly from a plugin code. They need to be called on plugins_loaded hook or later, for example on init hook.

Function replacement (override) — in must-use or regular plugin you can create a function with the same name, then it will replace this function.

Uses: wp_rand()
1 time — 0.000068 sec (very fast) | 50000 times — 1.32 sec (fast) | PHP 7.0.4, WP 4.4.2
Hooks from the function

Return

String. The random password.

Usage

$password = wp_generate_password( $length, $special_chars, $extra_special_chars );
$length(int)
Password length. The number of characters in the password.
Default: 12
$special_chars(true/false)
Whether to include standard special characters: !@#$%^&*()
Default: true
$extra_special_chars(true/false)
Whether to include other special characters. Used when generating secret keys and salts: -_ []{}<>~`+=,.;:/?|
Default: false

Examples

0

#1 Generate a password and display it

Various examples of password generation:

echo wp_generate_password();                 // @iU!ZnjUWZsg
echo wp_generate_password( 15, false );      // YdD6j750MeiOkPa
echo wp_generate_password( 15, true, true ); // .WfvgX6`V^Vg:,_

Changelog

Since 2.5.0 Introduced.

wp_generate_password() code WP 6.5.2

function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) {
	$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	if ( $special_chars ) {
		$chars .= '!@#$%^&*()';
	}
	if ( $extra_special_chars ) {
		$chars .= '-_ []{}<>~`+=,.;:/?|';
	}

	$password = '';
	for ( $i = 0; $i < $length; $i++ ) {
		$password .= substr( $chars, wp_rand( 0, strlen( $chars ) - 1 ), 1 );
	}

	/**
	 * Filters the randomly-generated password.
	 *
	 * @since 3.0.0
	 * @since 5.3.0 Added the `$length`, `$special_chars`, and `$extra_special_chars` parameters.
	 *
	 * @param string $password            The generated password.
	 * @param int    $length              The length of password to generate.
	 * @param bool   $special_chars       Whether to include standard special characters.
	 * @param bool   $extra_special_chars Whether to include other special characters.
	 */
	return apply_filters( 'random_password', $password, $length, $special_chars, $extra_special_chars );
}
vladlu 100vlad.lu
Editors: Kama 247
2 comments
    Log In