Implement an API endpoint for facilitating a password reset email in WordPress

Add this to your theme’s functions.php or create a custom plugin

function custom_password_reset_endpoint() {
register_rest_route('custom/v1', '/password-reset/', array(
'methods' => 'POST',
'callback' => 'custom_password_reset_callback',
));
}
function custom_password_reset_callback($request) {
$email = sanitize_email($request->get_param('email'));
// Check if the email is associated with a user account
$user = get_user_by('email', $email);

if (!$user) {
    return new WP_Error('invalid_email', 'Invalid email address.', array('status' => 400));
}

// Generate a reset key
$reset_key = get_password_reset_key($user);

// Check if the key was generated successfully
if (is_wp_error($reset_key)) {
    return new WP_Error('key_generation_error', 'Error generating reset key.', array('status' => 500));
}

// Generate the default WordPress reset link
$reset_link = esc_url_raw(add_query_arg(
    array(
        'action' => 'rp',
        'key'    => $reset_key,
        'login'  => rawurlencode($user->user_login),
    ),
    site_url('wp-login.php', 'login')
));

// Implement your email sending logic here
$email_subject = 'Password Reset Request';
$email_message = 'Someone has requested a password reset for the following account:' . "\r\n\r\n";
$email_message .= 'Site Name: ' . get_bloginfo('name') . "\r\n";
$email_message .= 'Username: ' . $user->user_login . "\r\n\r\n";
$email_message .= 'If this was a mistake, ignore this email and nothing will happen.' . "\r\n\r\n";
$email_message .= 'To reset your password, visit the following address:' . "\r\n\r\n";
$email_message .= $reset_link;

wp_mail($email, $email_subject, $email_message);

return array('message' => 'Password reset link sent successfully.');
}
add_action('rest_api_init', 'custom_password_reset_endpoint');

The endpoint defined in the code is:
/custom/v1/password-reset/

body of the API:

{ “email”:”email@gmail.com”}

Leave a comment

Your email address will not be published. Required fields are marked *