以前我只會按下「啟用佈景主題」,從沒想過背後如何處理。
今天就讓我帶你一起來了解 WordPress 主題切換時,實際運作的邏輯!
switch_theme:當主題被切換時觸發
當你的主題被「切換」時,會觸發 switch_theme
。
這通常用來執行以下行為:
- 清除先前主題的設定
- 刪除資料
- 寫入切換記錄等
語法:
do_action( 'switch_theme', string $new_name, WP_Theme $new_theme, WP_Theme $old_theme );
JavaScript使用範例:
add_action('switch_theme', function() {
delete_option('mytheme_color_scheme');
delete_option('mytheme_font_size');
});
JavaScript上述程式碼的作用是:
當主題被切換時,會自動移除自己儲存的設定值。
after_switch_theme:主題「啟用之後」才會觸發
這個 hook 是在主題被成功啟用「之後」才會觸發,
適合用來執行初始化邏輯、設定標記、或寄送通知等。
語法:
do_action( 'after_switch_theme', string $old_name, WP_Theme $old_theme );
JavaScript實用範例:
add_action('after_switch_theme', 'my_theme_activation_callback', 10, 2);
function my_theme_activation_callback( $old_name, $old_theme ) {
// 清除快取
wp_cache_flush();
// 記錄主題剛剛啟用
update_option('mytheme_just_activated', 'yes');
// 通知網站管理員
$admin_email = get_option('admin_email');
wp_mail(
$admin_email,
"Theme switched from {$old_name}",
"The theme on your site was switched from {$old_name} to " . get_option('stylesheet')
);
}
JavaScript解說:
'after_switch_theme'
:WordPress 提供的 hook 名稱'my_theme_activation_callback'
:當主題被啟用時執行的自訂函式10
:優先順序,數字越小越早執行2
:此函式接受兩個參數(舊主題名稱與 WP_Theme 物件)
多個函式時的執行順序
如果你有多個函式都綁在 after_switch_theme
,可以透過優先順序決定執行先後:
add_action( 'after_switch_theme', 'first_func', 5 );
add_action( 'after_switch_theme', 'second_func', 10 );
add_action( 'after_switch_theme', 'third_func', 20 );
實際執行順序:
first_func
(優先順序 5)second_func
(優先順序 10)third_func
(優先順序 20)
今天的內容就到這邊
Keep going, you’re getting stronger.
我們下篇文章見