check_theme_switched()
云策文档标注
概述
check_theme_switched() 函数用于检查主题是否已切换,并在下一次 WordPress 加载时触发 'after_switch_theme' 钩子。它处理主题切换后的清理和动作执行。
关键要点
- 检查 'theme_switched' 选项以确定主题是否已切换
- 如果通过 Customizer 切换主题,会移除菜单和小部件的映射动作
- 根据旧主题是否存在,以不同参数触发 'after_switch_theme' 钩子
- 执行 flush_rewrite_rules() 以更新重写规则
- 最后更新 'theme_switched' 选项为 false 以重置状态
代码示例
function check_theme_switched() {
$stylesheet = get_option( 'theme_switched' );
if ( $stylesheet ) {
$old_theme = wp_get_theme( $stylesheet );
// Prevent widget & menu mapping from running since Customizer already called it up front.
if ( get_option( 'theme_switched_via_customizer' ) ) {
remove_action( 'after_switch_theme', '_wp_menus_changed' );
remove_action( 'after_switch_theme', '_wp_sidebars_changed' );
update_option( 'theme_switched_via_customizer', false );
}
if ( $old_theme->exists() ) {
do_action( 'after_switch_theme', $old_theme->get( 'Name' ), $old_theme );
} else {
do_action( 'after_switch_theme', $stylesheet, $old_theme );
}
flush_rewrite_rules();
update_option( 'theme_switched', false );
}
}注意事项
- 此函数在 WordPress 核心中自动调用,开发者通常无需直接使用
- 'after_switch_theme' 钩子可用于在主题切换后执行自定义代码
- 通过 Customizer 切换主题时,会跳过菜单和小部件的默认映射以避免重复处理
原文内容
Checks if a theme has been changed and runs ‘after_switch_theme’ hook on the next WP load.
Description
See ‘after_switch_theme’.
Source
function check_theme_switched() {
$stylesheet = get_option( 'theme_switched' );
if ( $stylesheet ) {
$old_theme = wp_get_theme( $stylesheet );
// Prevent widget & menu mapping from running since Customizer already called it up front.
if ( get_option( 'theme_switched_via_customizer' ) ) {
remove_action( 'after_switch_theme', '_wp_menus_changed' );
remove_action( 'after_switch_theme', '_wp_sidebars_changed' );
update_option( 'theme_switched_via_customizer', false );
}
if ( $old_theme->exists() ) {
/**
* Fires on the next WP load after the theme has been switched.
*
* The parameters differ according to whether the old theme exists or not.
* If the old theme is missing, the old name will instead be the slug
* of the old theme.
*
* See 'switch_theme'.
*
* @since 3.3.0
*
* @param string $old_name Old theme name.
* @param WP_Theme $old_theme WP_Theme instance of the old theme.
*/
do_action( 'after_switch_theme', $old_theme->get( 'Name' ), $old_theme );
} else {
/** This action is documented in wp-includes/theme.php */
do_action( 'after_switch_theme', $stylesheet, $old_theme );
}
flush_rewrite_rules();
update_option( 'theme_switched', false );
}
}
Hooks
- do_action( ‘after_switch_theme’, string $old_name, WP_Theme $old_theme )
-
Fires on the next WP load after the theme has been switched.
Changelog
| Version | Description |
|---|---|
| 3.3.0 | Introduced. |