set_theme_mod()
云策文档标注
概述
set_theme_mod() 函数用于更新当前活动主题的主题修改值。它接受名称和值参数,通过更新主题选项来存储修改,并返回布尔值表示更新是否成功。
关键要点
- 函数签名:set_theme_mod( $name, $value ),其中 $name 是主题修改名称(字符串,必需),$value 是主题修改值(混合类型,必需)。
- 返回值:布尔值,true 表示更新成功,false 表示失败。
- 内部机制:函数首先获取当前主题修改数组,然后应用 pre_set_theme_mod_{$name} 过滤器,最后通过 update_option() 更新 theme_mods_$theme 选项。
- 相关 Hook:apply_filters( "pre_set_theme_mod_{$name}", $value, $old_value ),用于在保存前过滤主题修改值。
- 相关函数:包括 get_theme_mods()、apply_filters()、update_option() 和 get_option()。
- 使用场景:在 WordPress 核心和自定义功能中广泛使用,如菜单位置更新、自定义 CSS 设置等。
- 版本历史:自 2.1.0 引入,5.6.0 版本添加了返回值。
代码示例
function wecodeart_theme_mods() {
set_theme_mod('my_mod_one', 'new_mode_one_value');
}
add_action( 'init', 'wecodeart_theme_mods' );
原文内容
Updates theme modification value for the active theme.
Parameters
$namestringrequired-
Theme modification name.
$valuemixedrequired-
Theme modification value.
Source
function set_theme_mod( $name, $value ) {
$mods = get_theme_mods();
$old_value = isset( $mods[ $name ] ) ? $mods[ $name ] : false;
/**
* Filters the theme modification, or 'theme_mod', value on save.
*
* The dynamic portion of the hook name, `$name`, refers to the key name
* of the modification array. For example, 'header_textcolor', 'header_image',
* and so on depending on the theme options.
*
* @since 3.9.0
*
* @param mixed $value The new value of the theme modification.
* @param mixed $old_value The current value of the theme modification.
*/
$mods[ $name ] = apply_filters( "pre_set_theme_mod_{$name}", $value, $old_value );
$theme = get_option( 'stylesheet' );
return update_option( "theme_mods_$theme", $mods );
}
Hooks
- apply_filters( “pre_set_theme_mod_{$name}”, mixed $value, mixed $old_value )
-
Filters the theme modification, or ‘theme_mod’, value on save.
Skip to note 2 content
Bican Marian Valeriu
Sample usage, hooking into ‘init’
function wecodeart_theme_mods() { set_theme_mod('my_mod_one', 'new_mode_one_value'); } add_action( 'init', 'wecodeart_theme_mods' );