pre_option_{$option}
云策文档标注
概述
pre_option_{$option} 是一个 WordPress 过滤器钩子,用于在获取现有选项值之前临时修改其值,而不永久更改数据库中的存储。它允许开发者在特定视图渲染时动态调整选项,如博客名称或每页文章数。
关键要点
- 这是一个动态钩子,{$option} 部分对应选项名称,例如 pre_option_blogname 或 pre_option_posts_per_page。
- 过滤器返回非 false 值会短路选项检索过程,直接返回该值,跳过默认的 get_option() 逻辑。
- 参数包括 $pre_option(预选项值,默认 false)、$option(选项名称)和 $default_value(选项不存在时的回退值,默认 false)。
- 适用于临时修改选项,例如基于页面条件(如首页或特定分类)调整设置,而无需永久更新数据库。
- 可通过 wp_load_alloptions() 获取所有可用选项列表,用于调试或参考。
代码示例
// 示例1:在首页过滤 blogname 选项
function wp_docs_pre_filter_option( $pre_option ) {
if ( ! is_home() ) {
return $pre_option;
}
return 'My Awesome Homepage';
}
add_filter( 'pre_option_blogname', 'wp_docs_pre_filter_option' );
// 示例2:针对特定分类修改每页文章数
add_filter('pre_option_posts_per_page', 'limit_posts_per_page');
function limit_posts_per_page( $posts_per_page ) {
global $wp_query;
if ( $wp_query->query_vars['category_name'] == 'foo' ) {
return 20;
}
return $posts_per_page;
}注意事项
- 此钩子从 WordPress 1.5.0 版本引入,$option 参数在 4.4.0 添加,$default_value 参数在 4.9.0 添加。
- 主要用于 get_option() 函数中,避免在不需要时永久更改选项值。
- 确保过滤器逻辑正确,避免意外影响其他页面或功能。
原文内容
Filters the value of an existing option before it is retrieved.
Description
The dynamic portion of the hook name, $option, refers to the option name.
Returning a value other than false from the filter will short-circuit retrieval and return that value instead.
Parameters
$pre_optionmixed-
The value to return instead of the option value. This differs from
$default_value, which is used as the fallback value in the event the option doesn’t exist elsewhere in get_option() .
Default false (to skip past the short-circuit). $optionstring-
Option name.
$default_valuemixed-
The fallback value to return if the option does not exist.
Default false.
Source
$pre = apply_filters( "pre_option_{$option}", false, $option, $default_value );
Skip to note 3 content
Drew Jaynes
Example: Filter the
blognameoption on the homepage/** * Filters the blogname option on the homepage. * * @param false|mixed $value Pre-option value. Default false. * @return false|mixed (Maybe) filtered pre-option value. */ function wp_docs_pre_filter_option( $pre_option ) { if ( ! is_home() ) { return $pre_option; } return 'My Awesome Homepage'; } add_filter( 'pre_option_blogname', 'wp_docs_pre_filter_option' );Skip to note 4 content
Steven Lin
Example migrated from Codex:
The example below shows how to alter the amount of displayed posts per page for a specific category (here, the ‘foo’ category). The code is added to the
functions.phpfile of the theme.add_filter('pre_option_posts_per_page', 'limit_posts_per_page'); function limit_posts_per_page( $posts_per_page ) { global $wp_query; if ( $wp_query->query_vars['category_name'] == 'foo' ) { return 20; } return $posts_per_page; }