wp_nonce_ays()
云策文档标注
概述
wp_nonce_ays() 函数用于显示“您确定吗?”消息以确认操作,常用于安全验证场景。它根据提供的 nonce 动作参数生成相应的确认页面,并在用户未通过验证时终止执行。
关键要点
- 函数接受一个必需的字符串参数 $action,指定 nonce 动作。
- 默认情况下,显示错误消息并返回 403 响应码。
- 当 $action 为 'log-out' 时,会生成特定的注销确认页面,包含站点标题和注销链接。
- 对于其他动作,显示链接已过期的消息,并可提供返回链接。
- 函数内部调用了 wp_die() 来终止执行并输出 HTML 页面。
代码示例
function wp_nonce_ays( $action ) {
// 默认标题和响应码
$title = __( 'An error occurred.' );
$response_code = 403;
if ( 'log-out' === $action ) {
$title = sprintf(
/* translators: %s: Site title. */
__( 'You are attempting to log out of %s' ),
get_bloginfo( 'name' )
);
$redirect_to = isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '';
$html = $title;
$html .= '';
$html .= sprintf(
/* translators: %s: Logout URL. */
__( 'Do you really want to log out?' ),
wp_logout_url( $redirect_to )
);
} else {
$html = __( 'The link you followed has expired.' );
if ( wp_get_referer() ) {
$wp_http_referer = remove_query_arg( 'updated', wp_get_referer() );
$wp_http_referer = wp_validate_redirect( sanitize_url( $wp_http_referer ) );
$html .= '';
$html .= sprintf(
'%s',
esc_url( $wp_http_referer ),
__( 'Please try again.' )
);
}
}
wp_die( $html, $title, $response_code );
}注意事项
- 此函数主要用于内部安全验证,如 check_admin_referer() 调用时触发。
- 用户贡献笔记中提到,可以通过传递 'log-out' 作为参数来用于注销确认。
- 确保在需要验证用户意图的场景中使用,以避免非预期操作。
原文内容
Displays “Are You Sure” message to confirm the action being taken.
Description
If the action has the nonce explain message, then it will be displayed along with the “Are you sure?” message.
Parameters
$actionstringrequired-
The nonce action.
Source
function wp_nonce_ays( $action ) {
// Default title and response code.
$title = __( 'An error occurred.' );
$response_code = 403;
if ( 'log-out' === $action ) {
$title = sprintf(
/* translators: %s: Site title. */
__( 'You are attempting to log out of %s' ),
get_bloginfo( 'name' )
);
$redirect_to = isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '';
$html = $title;
$html .= '</p><p>';
$html .= sprintf(
/* translators: %s: Logout URL. */
__( 'Do you really want to <a href="%s">log out</a>?' ),
wp_logout_url( $redirect_to )
);
} else {
$html = __( 'The link you followed has expired.' );
if ( wp_get_referer() ) {
$wp_http_referer = remove_query_arg( 'updated', wp_get_referer() );
$wp_http_referer = wp_validate_redirect( sanitize_url( $wp_http_referer ) );
$html .= '</p><p>';
$html .= sprintf(
'<a href="%s">%s</a>',
esc_url( $wp_http_referer ),
__( 'Please try again.' )
);
}
}
wp_die( $html, $title, $response_code );
}
Changelog
| Version | Description |
|---|---|
| 2.0.4 | Introduced. |
Skip to note 2 content
Alvaro Torres
We can use it to log-out by using log-out as argument:
wp_nonce_ays('log-out');