Wordpress 仅当激活主题时才在functions.php中运行代码块。使用寄存器\激活\挂钩?
我有一个特定的设置代码为我的主题,我只想处理时,主题是第一次激活位。我的印象是我可以使用register\u activation\u hook来实现这一点,但它似乎不起作用 例如 在我的functions.php文件中,我希望doThemeSetup()函数只在主题激活时运行,而不在其他时间运行Wordpress 仅当激活主题时才在functions.php中运行代码块。使用寄存器\激活\挂钩?,wordpress,themes,Wordpress,Themes,我有一个特定的设置代码为我的主题,我只想处理时,主题是第一次激活位。我的印象是我可以使用register\u activation\u hook来实现这一点,但它似乎不起作用 例如 在我的functions.php文件中,我希望doThemeSetup()函数只在主题激活时运行,而不在其他时间运行 function doThemeSetup(){ //stuff here only runs once, when theme is activated } register_activati
function doThemeSetup(){
//stuff here only runs once, when theme is activated
}
register_activation_hook(__FILE__, 'doThemeSetup');
更新:自从发布这个问题以来,我发现register\u activation\u hook只适用于插件,而不适用于主题
我已经找到了一种在主题中执行类似操作的方法,但结果不一致:
if ( is_admin() && isset($_GET['activated'] ) && $pagenow == 'themes.php' )
{
//do something
}
上面的代码似乎不是在主题首次激活时运行的,而是在主题从另一个主题切换到另一个主题时运行的。这更像是一种解决方法,而不是解决方案,但是如果所有其他方法都失败了,您可以尝试:
<?php
if (get_option('themename_installed') != 'true'){
if (doThemeSetup()){
add_option('themename_installed','true');
}
}
?>
这样,doThemeSetup只运行一次
/**
* Install script to create databasetables and then insert default data.
* And inserting defautl theame settings.
* Only run if theme is being activated for the first time.
*/
$flag = get_option('first_time_theme_activation_check');
if ( $flag == false && is_admin())
{
// put your code to run when theme is activated at first time by admin
// update option at last
update_option('first_time_theme_activation_check', 'true');
}