send password reset link code wp
To send a password reset link in WordPress, you can use the following code:
function send_password_reset_link() {
if ( isset( $_POST['user_login'] ) && $_POST['user_login'] ) {
$user_login = $_POST['user_login'];
$user_data = get_user_by( 'login', $user_login );
if ( ! $user_data ) {
return;
}
$user_email = $user_data->user_email;
$reset_key = get_password_reset_key( $user_data );
$reset_url = site_url( "wp-login.php?action=rp&key=$reset_key&login=" . rawurlencode( $user_login ), 'login' );
$message = "Please click the following link to reset your password: $reset_url";
wp_mail( $user_email, 'Password Reset', $message );
wp_safe_redirect( wp_login_url() );
exit;
}
}
add_action( 'login_form_lostpassword', 'send_password_reset_link' );
Here is an explanation of each step:
Step 1: Create a function named
send_password_reset_link()
that will be triggered when the user submits the password reset form.Step 2: Check if the
user_login
field is set in the$_POST
array and if it has a value. This ensures that the user has entered a username or email address.Step 3: Retrieve the user data based on the provided
user_login
using theget_user_by()
function. If no user is found, the function will return early.Step 4: Get the user's email address from the user data.
Step 5: Generate a password reset key for the user using the
get_password_reset_key()
function. This key will be used to verify the user's identity when resetting the password.Step 6: Create the reset URL by appending the reset key and the user's login to the login page URL. The
site_url()
function is used to get the base URL of the site.Step 7: Compose the message for the email, including the reset URL.
Step 8: Use the
wp_mail()
function to send the password reset link to the user's email address.Step 9: Redirect the user to the login page using the
wp_safe_redirect()
function.Step 10: Exit the script to prevent further execution.
Step 11: Hook the
send_password_reset_link()
function to thelogin_form_lostpassword
action. This ensures that the function is called when the password reset form is submitted.
By following these steps, you can implement a code snippet to send a password reset link in WordPress.