钩子文档

after_switch_theme

💡 云策文档标注

概述

after_switch_theme 是一个 WordPress 动作钩子,在主题切换后的下一次 WordPress 加载时触发。它主要用于在激活新主题时执行初始化或设置操作,例如设置默认选项或更新配置。

关键要点

  • 触发时机:在主题切换后的下一次 WordPress 加载时触发。
  • 参数:根据旧主题是否存在而不同,包括 $old_name(字符串,旧主题名称)和 $old_theme(WP_Theme 实例)。
  • 回调函数仅在被激活的主题(和/或子主题)中触发,不适用于主题停用场景。
  • 相关函数:check_theme_switched() 用于检查主题是否已更改并运行此钩子。
  • 版本历史:从 WordPress 3.3.0 版本引入。

代码示例

// 示例1:为主题添加默认选项
add_action('after_switch_theme', 'mytheme_setup_options');

function mytheme_setup_options () {
  add_option('mytheme_enable_catalog', 0);
  add_option('mytheme_enable_features', 0);
}

// 示例2:更新默认中等图像尺寸
function example_update_default_image_size( $old_theme_name, $old_theme = false ) {
	update_option( 'medium_size_w', 800 );
	update_option( 'medium_size_h', 400 );
}
add_action( 'after_switch_theme', 'example_update_default_image_size', 10, 2 );

注意事项

  • 此钩子仅在主题激活时触发,如需在主题停用时执行操作,应使用 switch_theme 钩子。
  • 参数 $old_theme 可能为 false,需在回调函数中处理旧主题不存在的情况。

📄 原文内容

Fires on the next WP load after the theme has been switched.

Description

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’.

Parameters

$old_namestring
Old theme name.
$old_themeWP_Theme
WP_Theme instance of the old theme.

More Information

Callback functions attached to this hook are only triggered in the theme (and/or child theme) being activated. To do things when your theme is deactivated, use switch_theme.

Source

do_action( 'after_switch_theme', $old_theme->get( 'Name' ), $old_theme );

Changelog

Version Description
3.3.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Update the default medium image size when a theme is activated.

    function example_update_default_image_size( $old_theme_name, $old_theme = false ) {
    	update_option( 'medium_size_w', 800 );
    	update_option( 'medium_size_h', 400 );
    }
    add_action( 'after_switch_theme', 'example_update_default_image_size', 10, 2 );