我以前只會按下「啟用佈景主題」,從沒想過背後如何處理。
今天就讓我帶你一起來了解 WordPress 主題切換時,實際運作的邏輯!
switch_theme、after_switch_theme是什麼呢?
當你的主題被「切換」時,會觸發 switch_theme
。
這通常用來執行cleanup、資料移除、寫入記錄等工作。
do_action( 'switch_theme', string $new_name, WP_Theme $new_theme, WP_Theme $old_theme );
add_action('switch_theme', function() {
delete_option('mytheme_color_scheme');
delete_option('mytheme_font_size');
});
上方範例功能:當主題被切換時,移除自己曾儲存的設定值。
這個hook會在主題「被啟用之後」觸發,可用來執行初始化邏輯。
do_action( 'after_switch_theme', string $old_name, WP_Theme $old_theme );
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')
);
}
'after_switch_theme'
:WordPress的hook名稱'my_theme_activation_callback'
:你要執行的函式10
:優先順序(數字越小越早執行)2
:此函式接受兩個參數(舊主題名稱與物件)假設你有多個函式要在 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.
下篇文章,見~