钩子文档

switch_theme

💡 云策文档标注

概述

switch_theme 是一个 WordPress 动作钩子,在主题切换后触发,主要用于主题停用时的清理或设置操作。它允许开发者在主题被停用时执行特定函数,例如刷新重写规则或删除选项。

关键要点

  • switch_theme 在博客主题更改后触发,但在下一个请求之前执行。
  • 此钩子仅在被停用的主题中触发,适用于主题停用时的操作;主题激活时应使用 after_switch_theme。
  • 钩子函数接收一个参数:新主题名称的字符串,但实际源参数包括 $new_name、$new_theme 和 $old_theme。
  • 从 WordPress 4.5.0 版本开始引入了 $old_theme 参数,提供旧主题的 WP_Theme 实例。

代码示例

function deactivate_my_theme( $new_theme ) {
    flush_rewrite_rules(false);
}
add_action( 'switch_theme', 'deactivate_my_theme' );
add_action('switch_theme', 'mytheme_setup_options');

function mytheme_setup_options () {
  delete_option('mytheme_enable_features');
  delete_option('mytheme_enable_catalog');
}

注意事项

确保在主题停用时使用此钩子,避免与激活操作混淆;参数传递需注意版本差异,特别是 $old_theme 在 4.5.0 及之后可用。


📄 原文内容

Fires after the theme is switched.

Description

See ‘after_switch_theme’.

Parameters

$new_namestring
Name of the new theme.
$new_themeWP_Theme
WP_Theme instance of the new theme.
$old_themeWP_Theme
WP_Theme instance of the old theme.

More Information

switch_theme is triggered when the blog’s theme is changed. Specifically, it fires after the theme has been switched but before the next request. Theme developers should use this hook to do things when their theme is deactivated.

Theme functions attached to this hook are only triggered in the theme being deactivated. To do things when your theme is activated, use after_switch_theme.

Functions attached to this action hook receive one parameter: a string with the name of the new theme being activated.

Source

do_action( 'switch_theme', $new_name, $new_theme, $old_theme );

Changelog

Version Description
4.5.0 Introduced the $old_theme parameter.
1.5.0 Introduced.

User Contributed Notes