wp_ajax_send_password_reset()
云策文档标注
概述
wp_ajax_send_password_reset() 是一个 WordPress AJAX 处理函数,用于通过 AJAX 发送密码重置链接。它验证 nonce 和用户权限,并调用 retrieve_password() 发送重置邮件。
关键要点
- 函数用于处理 AJAX 请求,发送密码重置链接给指定用户。
- 验证 nonce 以确保请求安全性,使用 check_ajax_referer()。
- 检查当前用户是否有编辑目标用户的权限,使用 current_user_can()。
- 调用 retrieve_password() 发送重置邮件,并根据结果返回 JSON 成功或错误响应。
- 相关函数包括 get_userdata()、wp_send_json_success() 和 wp_send_json_error()。
代码示例
// Validate the nonce for this action.
$user_id = isset( $_POST['user_id'] ) ? (int) $_POST['user_id'] : 0;
check_ajax_referer( 'reset-password-for-' . $user_id, 'nonce' );
// Verify user capabilities.
if ( ! current_user_can( 'edit_user', $user_id ) ) {
wp_send_json_error( __( 'Cannot send password reset, permission denied.' ) );
}
// Send the password reset link.
$user = get_userdata( $user_id );
$results = retrieve_password( $user->user_login );
if ( true === $results ) {
wp_send_json_success(
/* translators: %s: User's display name. */
sprintf( __( 'A password reset link was emailed to %s.' ), $user->display_name )
);
} else {
wp_send_json_error( $results->get_error_message() );
}注意事项
- 此函数自 WordPress 5.7.0 版本引入。
- 需要确保 AJAX 请求正确传递 user_id 和 nonce 参数。
- 错误处理依赖于 retrieve_password() 返回的 WP_Error 对象。
原文内容
Handles sending a password reset link via AJAX.
Source
function wp_ajax_send_password_reset() {
// Validate the nonce for this action.
$user_id = isset( $_POST['user_id'] ) ? (int) $_POST['user_id'] : 0;
check_ajax_referer( 'reset-password-for-' . $user_id, 'nonce' );
// Verify user capabilities.
if ( ! current_user_can( 'edit_user', $user_id ) ) {
wp_send_json_error( __( 'Cannot send password reset, permission denied.' ) );
}
// Send the password reset link.
$user = get_userdata( $user_id );
$results = retrieve_password( $user->user_login );
if ( true === $results ) {
wp_send_json_success(
/* translators: %s: User's display name. */
sprintf( __( 'A password reset link was emailed to %s.' ), $user->display_name )
);
} else {
wp_send_json_error( $results->get_error_message() );
}
}
Changelog
| Version | Description |
|---|---|
| 5.7.0 | Introduced. |