set-screen-option
云策文档标注
概述
set-screen-option 是一个 WordPress 过滤器,用于在设置屏幕选项值之前进行过滤。它允许开发者修改标准或非标准的选项值,例如每页显示项目数,并可通过返回 false 来跳过保存当前选项。
关键要点
- 过滤器名称:set-screen-option,用于在保存屏幕选项前过滤值。
- 参数:$screen_option(要保存的选项值,默认 false 以跳过保存)、$option(选项名称)、$value(选项值)。
- 应用范围:仅适用于以 '_page' 结尾的选项或 'layout_columns' 选项,从 WordPress 5.4.2 开始。
- 钩子时机:必须在 WordPress 动作栈中较早调用,例如在 'init' 钩子中,以避免因调用过晚而无法触发。
- 优先级设置:建议设置优先级大于 10 以确保过滤器正确工作,避免过早调用导致过滤无效。
代码示例
add_filter('set-screen-option', 'myFilterScreenOption', 11, 3);
function myFilterScreenOption($keep, $option, $value) {
if ($option === 'myitem_per_page') {
if ($value > 100) {
$value = 100;
}
}
return $value;
}注意事项
- 避免在 'admin_menu' 钩子等较晚的时机添加此过滤器,否则可能无法生效。
- 与 add_screen_option() 配合使用时,保存选项的过滤器应在设置选项之前调用,遵循“先保存后设置”的原则。
原文内容
Filters a screen option value before it is set.
Description
The filter can also be used to modify non-standard [items]_per_page settings. See the parent function for a full list of standard options.
Returning false from the filter will skip saving the current option.
See also
Parameters
$screen_optionmixed-
The value to save instead of the option value.
Default false (to skip saving the current option). $optionstring-
The option name.
$valueint-
The option value.
Source
$screen_option = apply_filters( 'set-screen-option', $screen_option, $option, $value ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
Skip to note 3 content
Lance Cleveland
This cannot be called too late in the WordPress action stack or it will not fire at the right time. You cannot put it inside a function running during the ‘admin_menu’ hook, for example. For the Store Locator Plus plugin (you can find up-to-date working code buried in there) I find adding the filter inside the WordPress ‘init’ methods works best as this is called early in the WordPress action stack.
The “sister” add_screen_option() call, however, tends to work better later in the call stack such as within the ‘admin_menu’ hook.
The general premise: save the options goes before (WP ‘init’ hook) setting up the options (WP ‘admin_menu’ hook).
Skip to note 4 content
vee
To make it really work and easy to understand.
This code will NOT work.
add_filter('set-screen-option', 'myFilterScreenOption', 10, 3); function myFilterScreenOption($keep, $option, $value) { if ($option === 'myitem_per_page') { if ($value < 0) { $value = 0; } elseif ($value > 100) { $value = 100; } } return $value; }If you enter 200 as item per page, it will still be 200 not 100 because you call to this filter too early.
This code will work.
add_filter('set-screen-option', 'myFilterScreenOption', 11, 3); function myFilterScreenOption($keep, $option, $value) { if ($option === 'myitem_per_page') { if ($value < 0) { $value = 0; } elseif ($value > 100) { $value = 100; } } return $value; }Just add priority to more than 10.
Tested in WordPress 5.1