Using WordPress ‘get_password_reset_key()’ PHP function

The get_password_reset_key() WordPress PHP function creates, stores, and returns a password reset key for a user.

Usage

$reset_key = get_password_reset_key( $user );

Input:

  • $user: a WP_User object

Output:

  • The password reset key as a string

Parameters

  • $user (WP_User): The user object for which you want to retrieve a password reset key.

More information

See WordPress Developer Resources: get_password_reset_key

Examples

Generate a password reset key for a user with a known ID

Retrieve the user object for a user with ID 5, and then generate a password reset key for that user.

$user_id = 5;
$user = get_user_by( 'id', $user_id );
$reset_key = get_password_reset_key( $user );

Generate a password reset key for a user with a known email

Retrieve the user object for a user with email ‘[email protected]’, and then generate a password reset key for that user.

$user_email = '[email protected]';
$user = get_user_by( 'email', $user_email );
$reset_key = get_password_reset_key( $user );

Generate a password reset key for a user with a known username

Retrieve the user object for a user with username ‘john’, and then generate a password reset key for that user.

$username = 'john';
$user = get_user_by( 'login', $username );
$reset_key = get_password_reset_key( $user );

Generate a password reset key for the current user

Retrieve the user object for the currently logged-in user, and then generate a password reset key for that user.

$current_user = wp_get_current_user();
$reset_key = get_password_reset_key( $current_user );

Generate a password reset key and send an email to the user

Retrieve the user object for a user with email ‘[email protected]’, generate a password reset key, and then send an email to the user with a link to reset their password.

$user_email = '[email protected]';
$user = get_user_by( 'email', $user_email );
$reset_key = get_password_reset_key( $user );

$message = 'Click on the following link to reset your password: ';
$message .= wp_lostpassword_url( $reset_key );

wp_mail( $user_email, 'Password Reset', $message );