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:

  1. Step 1: Create a function named send_password_reset_link() that will be triggered when the user submits the password reset form.

  2. 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.

  3. Step 3: Retrieve the user data based on the provided user_login using the get_user_by() function. If no user is found, the function will return early.

  4. Step 4: Get the user's email address from the user data.

  5. 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.

  6. 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.

  7. Step 7: Compose the message for the email, including the reset URL.

  8. Step 8: Use the wp_mail() function to send the password reset link to the user's email address.

  9. Step 9: Redirect the user to the login page using the wp_safe_redirect() function.

  10. Step 10: Exit the script to prevent further execution.

  11. Step 11: Hook the send_password_reset_link() function to the login_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.