Using WordPress ‘generate_random_password()’ PHP function

The generate_random_password() WordPress PHP function generates a random password.

Usage

generate_random_password( $len )

Example:

Input: generate_random_password(12)

Output: A3bd5G%h1@Kj

Parameters

  • $len (int) – Optional. The length of the password to generate. Default is 8.

More information

See WordPress Developer Resources: generate_random_password

Examples

Generate a Default-Length Random Password

Generate an 8-character random password.

$random_password = generate_random_password();
echo $random_password; // Output: J8$2kP!q

Generate a Custom-Length Random Password

Generate a 15-character random password.

$random_password = generate_random_password(15);
echo $random_password; // Output: T!y7@H$1p^3aD*W

Create a New User with a Random Password

Create a new user with a random 10-character password.

$new_user_data = array(
    'user_login' => 'new_user',
    'user_pass' => generate_random_password(10),
    'user_email' => '[email protected]',
);

$user_id = wp_insert_user($new_user_data);

Reset a User’s Password to a Random Password

Reset a user’s password to a random 12-character password.

$user_id = 2; // User ID
$new_password = generate_random_password(12);
wp_set_password($new_password, $user_id);

Generate a Random Password and Send it via Email

Generate a random 10-character password and send it to the user’s email.

$user = get_user_by('email', '[email protected]');
$new_password = generate_random_password(10);
wp_set_password($new_password, $user->ID);

$message = "Your new password is: {$new_password}";
wp_mail($user->user_email, 'New Password', $message);