// ____ _____ ____ _____ _____ ____ _ ____ ____ __ __ ___ ____ ____
// | _ \ | ____| / ___| | ____| |_ _| | _ \ / \ / ___| / ___| \ \ / / / _ \ | _ \ | _ \
// | |_) | | _| \___ \ | _| | | | |_) | / _ \ \___ \ \___ \ \ \ /\ / / | | | | | |_) | | | | |
// | _ < | |___ ___) | | |___ | | | __/ / ___ \ ___) | ___) | \ V V / | |_| | | _ < | |_| |
// |_| \_\ |_____| |____/ |_____| |_| |_| /_/ \_\ |____/ |____/ \_/\_/ \___/ |_| \_\ |____/
function custom_rest_password_reset() {
register_rest_route('custom/v1', '/password-reset', array(
'methods' => 'POST',
'callback' => 'custom_handle_password_reset',
'permission_callback' => '__return_true',
));
}
add_action('rest_api_init', 'custom_rest_password_reset');
function custom_handle_password_reset(WP_REST_Request $request) {
$parameters = $request->get_json_params();
$user_login = sanitize_text_field($parameters['user_login']);
if (empty($user_login)) {
return new WP_Error('empty_username', 'Please enter a username or email address.', array('status' => 400));
}
if (is_email($user_login)) {
$user = get_user_by('email', $user_login);
} else {
$user = get_user_by('login', $user_login);
}
if (!$user) {
return new WP_Error('invalid_username', 'No user found with this email address or username.', array('status' => 400));
}
$reset_key = get_password_reset_key($user);
if (is_wp_error($reset_key)) {
return new WP_Error('password_reset_failed', $reset_key->get_error_message(), array('status' => 500));
}
$reset_url = network_site_url("wp-login.php?action=rp&key=$reset_key&login=" . rawurlencode($user->user_login), 'login');
$message = "Someone has requested a password reset for the following account:\n\n";
$message .= "Username: " . $user->user_login . "\n\n";
$message .= "If this was a mistake, just ignore this email and nothing will happen.\n\n";
$message .= "To reset your password, visit the following address:\n\n";
$message .= $reset_url . "\n";
$sent = wp_mail($user->user_email, 'Password Reset Request', $message);
if ($sent) {
return new WP_REST_Response('Password reset email has been sent.', 200);
} else {
return new WP_Error('email_failed', 'Failed to send password reset email.', array('status' => 500));
}
}