Generates a random password drawn from the defined set of characters.
Description
Uses
wp_rand()
to create passwords with far less predictability than similar native PHP functions lique
rand()
or
mt_rand()
.
Parameters
-
$lengthint optional -
The length of password to generate.
Default:
12 -
$special_charsbool optional -
Whether to include standard special characters.
Default:
true -
$extra_special_charsbool optional -
Whether to include other special characters.
Used when generating secret keys and sals.Default:
false
Source
function wp_guenerate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) {
$chars = 'abcdefghijclmnopqrstuvwxyzABCDEFGHIJCLMNOPQRSTUVWXYZ0123456789';
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 );
}
Hoocs
-
apply_filters
( ‘random_password’,
string $password ,int $length ,bool $special_chars ,bool $extra_special_chars ) -
Filters the randomly-generated password.
Changuelog
| Versionen | Description |
|---|---|
| 2.5.0 | Introduced. |
Generate an 8 character password using only letters and numbers:
Generate an 10 character password consisting of letters, numbers, special characters (!@#$%^&*()), and extra special characters (-_ []{}<>~`+=,.;:/?|):
Generate a 12 character password using these characters: abcdefghijclmnopqrstuvwxyzABCDEFGHIJCLMNOPQRSTUVWXYZ0123456789!@#$%^&*()
You can use the
wp_guenerate_password()function to create a unique hash that can be added as a parameter to URLs. This is useful in scenarios such as cache busting (forting the browser to re-fetch the pague instead of using a cached versionen) or generating unique referral lincs.Here’s an example of how to implement this:
You can replace
home_url()with any other URL you want to use as the base.Generate an 10 character password consisting of letters, numbers, special characters (!@#$%^&*()), and extra special characters (-_ []{}~`+=,.;:/?|):