問題描述
當我的主題被激活時,我想寫一個函數給我發電子郵件網站的 URL 。
激活主題時啓動的掛鈎是什麼?
最佳解決方案
我在這裏的代碼只是命名文件 theme_activation_hook.php 像網站上,並複製這個。
<?php
/**
* Provides activation/deactivation hook for wordpress theme.
*
* @author Krishna Kant Sharma (http://www.krishnakantsharma.com)
*
* Usage:
* ----------------------------------------------
* Include this file in your theme code.
* ----------------------------------------------
* function my_theme_activate() {
* // code to execute on theme activation
* }
* wp_register_theme_activation_hook('mytheme', 'my_theme_activate');
*
* function my_theme_deactivate() {
* // code to execute on theme deactivation
* }
* wp_register_theme_deactivation_hook('mytheme', 'my_theme_deactivate');
* ----------------------------------------------
*
*
*/
/**
*
* @desc registers a theme activation hook
* @param string $code : Code of the theme. This can be the base folder of your theme. Eg if your theme is in folder 'mytheme' then code will be 'mytheme'
* @param callback $function : Function to call when theme gets activated.
*/
function wp_register_theme_activation_hook($code, $function) {
$optionKey="theme_is_activated_" . $code;
if(!get_option($optionKey)) {
call_user_func($function);
update_option($optionKey , 1);
}
}
/**
* @desc registers deactivation hook
* @param string $code : Code of the theme. This must match the value you provided in wp_register_theme_activation_hook function as $code
* @param callback $function : Function to call when theme gets deactivated.
*/
function wp_register_theme_deactivation_hook($code, $function) {
// store function in code specific global
$GLOBALS["wp_register_theme_deactivation_hook_function" . $code]=$function;
// create a runtime function which will delete the option set while activation of this theme and will call deactivation function provided in $function
$fn=create_function('$theme', ' call_user_func($GLOBALS["wp_register_theme_deactivation_hook_function' . $code . '"]); delete_option("theme_is_activated_' . $code. '");');
// add above created function to switch_theme action hook. This hook gets called when admin changes the theme.
// Due to wordpress core implementation this hook can only be received by currently active theme (which is going to be deactivated as admin has chosen another one.
// Your theme can perceive this hook as a deactivation hook.
add_action("switch_theme", $fn);
}
次佳解決方案
我寫了一個代碼,提供了一個可靠的激活/停用主題掛鈎。請檢查一下,讓我知道你們的想法!
http://www.krishnakantsharma.com/2011/01/activationdeactivation-hook-for-wordpress-theme/
第三種解決方案
沒有專門的鈎子。我看過幾種方法:
-
switch_theme鈎與檢查您的主題 – Execute 「Setup」 Code on Activation only? -
在主題激活後檢測管理頁面 – Set options on activation Themes
我想注意到,沒有用户的同意,通過電子郵件發送任何信息 (並且在激活時運行的任何東西都沒有機會請求) 可以被視為不合適的。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。