option_{$option}
云策文档标注
概述
option_{$option} 是一个 WordPress 过滤器钩子,用于在数据库查询后过滤现有选项的值。钩子名称中的动态部分 $option 对应选项名,允许开发者自定义选项的返回值。
关键要点
- 钩子名称:option_{$option},其中 $option 是动态的选项名称。
- 参数:$value(选项值,如果存储为序列化则自动反序列化)和 $option(选项名称)。
- 用途:过滤任何已存在数据库中的选项值,不适用于不存在的选项(此时应使用 default_option_{$option})。
- 版本历史:从 WordPress 1.5.0 引入,4.4.0 版本添加了 $option 参数。
代码示例
// 示例:过滤 active_plugins 选项以在运行时禁用插件
add_filter( 'option_active_plugins', function( $plugins ){
if ( $my_condition ) {
unset( $plugins['my-plugin-slug'] ); // 注意:实际键应为数字索引
}
return $plugins;
});
// 示例:过滤 blogdescription 选项,在归档页面添加页码
add_filter( 'option_blogdescription', 'my_theme_filter_blogdescription' );
function my_theme_filter_blogdescription( $description ) {
if ( ! is_archive() ) {
return $description;
}
global $page, $paged;
if ( ( $paged >= 2 || $page >= 2 ) && ! is_404() ) {
$description .= $description . sprintf( __( ' Page %d' ), max( $paged, $page ) );
}
return $description;
}注意事项
- 此钩子仅在选项存在于数据库时运行,无法过滤不存在的选项(返回 false 的情况)。
- 使用 active_plugins 选项时,注意 $plugins 数组的键是数字索引,而非插件 slug 字符串。
原文内容
Filters the value of an existing option.
Description
The dynamic portion of the hook name, $option, refers to the option name.
Parameters
$valuemixed-
Value of the option. If stored serialized, it will be unserialized prior to being returned.
$optionstring-
Option name.
Source
return apply_filters( "option_{$option}", maybe_unserialize( $value ), $option );
Skip to note 4 content
ptasker
Quick tip for disabling a plugin at run time using the ‘active_plugins’ option:
// Outputs an array of all plugins. var_dump( get_option( 'active_plugins' ) ); add_filter( 'option_active_plugins', function( $plugins ){ if ( $my_condition ) { unset( $plugins['my-plugin-slug'] ); } return $plugins; }); // Outputs an empty array. var_dump( get_option( 'active_plugins' ) );Skip to note 5 content
Rolf Allard van Hagen
Please note: this filter hook does NOT run when the option does NOT exist in the database. So it can only be used to filter existing options, not to filter the
falseresponse when there is no option found. For that, you’ll need the hookdefault_option_{$option}Skip to note 6 content
Steven Lin
Example migrated from Codex:
For example, to filter the blog description, you may use
option_blogdescription.In the following sample code, we change the blog description on archive pages to include a page number (i.e. changing to “Example description. Page 2“). This is a common usage scenario to avoid duplicate meta description error in Google Webmaster Tools.
add_filter( 'option_blogdescription', 'my_theme_filter_blogdescription' ); function my_theme_filter_blogdescription( $description ) { if ( ! is_archive() ) { return $description; } global $page, $paged; if ( ( $paged >= 2 || $page >= 2 ) && ! is_404() ) { $description .= $description . sprintf( __( ' Page %d' ), max( $paged, $page ) ); } return $description; }