is_protected_ajax_action()
云策文档标注
概述
is_protected_ajax_action() 函数用于判断当前处理的 Ajax 操作是否需要防止白屏死机(WSOD)。它检查请求是否为 Ajax 操作,并验证其 action 是否在受保护的列表中。
关键要点
- 函数返回布尔值:true 表示当前 Ajax 操作应受保护,false 表示不需要保护。
- 首先检查 wp_doing_ajax() 和 $_REQUEST['action'] 是否存在,否则返回 false。
- 内置受保护的 Ajax 操作包括编辑主题/插件文件、心跳、安装/更新插件/主题等。
- 可通过 wp_protected_ajax_actions 过滤器自定义受保护的 Ajax 操作列表。
代码示例
function is_protected_ajax_action() {
if ( ! wp_doing_ajax() ) {
return false;
}
if ( ! isset( $_REQUEST['action'] ) ) {
return false;
}
$actions_to_protect = array(
'edit-theme-plugin-file',
'heartbeat',
'install-plugin',
'install-theme',
'search-plugins',
'search-install-plugins',
'update-plugin',
'update-theme',
'activate-plugin',
);
$actions_to_protect = (array) apply_filters( 'wp_protected_ajax_actions', $actions_to_protect );
if ( ! in_array( $_REQUEST['action'], $actions_to_protect, true ) ) {
return false;
}
return true;
}注意事项
- 此函数仅在 WordPress 5.2.0 及以上版本可用。
- 受保护的 Ajax 操作列表可通过 wp_protected_ajax_actions 过滤器扩展或修改。
- 函数依赖于 wp_doing_ajax() 和 $_REQUEST['action'],确保在 Ajax 上下文中使用。
原文内容
Determines whether we are currently handling an Ajax action that should be protected against WSODs.
Source
function is_protected_ajax_action() {
if ( ! wp_doing_ajax() ) {
return false;
}
if ( ! isset( $_REQUEST['action'] ) ) {
return false;
}
$actions_to_protect = array(
'edit-theme-plugin-file', // Saving changes in the core code editor.
'heartbeat', // Keep the heart beating.
'install-plugin', // Installing a new plugin.
'install-theme', // Installing a new theme.
'search-plugins', // Searching in the list of plugins.
'search-install-plugins', // Searching for a plugin in the plugin install screen.
'update-plugin', // Update an existing plugin.
'update-theme', // Update an existing theme.
'activate-plugin', // Activating an existing plugin.
);
/**
* Filters the array of protected Ajax actions.
*
* This filter is only fired when doing Ajax and the Ajax request has an 'action' property.
*
* @since 5.2.0
*
* @param string[] $actions_to_protect Array of strings with Ajax actions to protect.
*/
$actions_to_protect = (array) apply_filters( 'wp_protected_ajax_actions', $actions_to_protect );
if ( ! in_array( $_REQUEST['action'], $actions_to_protect, true ) ) {
return false;
}
return true;
}
Hooks
- apply_filters( ‘wp_protected_ajax_actions’, string[] $actions_to_protect )
-
Filters the array of protected Ajax actions.
Changelog
| Version | Description |
|---|---|
| 5.2.0 | Introduced. |