我的functions.php 文件中有一些设置代码,用于设置永久链接并添加主题使用的类别。我只希望在首次激活主题时运行此代码。无需再次运行代码。但是,通过将其放置在functions.php 文件中,每次加载网站上的页面时都会运行它。
是否有替代方法可以使用,以便此代码仅在首次激活自定义主题时运行?
最佳答案
在wp-includes/theme.php中,您将找到函数switch_theme()
。它提供了一个 Action 钩子(Hook):
/**
* Switches current theme to new template and stylesheet names.
*
* @since unknown
* @uses do_action() Calls 'switch_theme' action on updated theme display name.
*
* @param string $template Template name
* @param string $stylesheet Stylesheet name.
*/
function switch_theme($template, $stylesheet) {
update_option('template', $template);
update_option('stylesheet', $stylesheet);
delete_option('current_theme');
$theme = get_current_theme();
do_action('switch_theme', $theme);
}
所以你可以在你的functions.php中使用它:
function my_activation_settings($theme)
{
if ( 'Your Theme Name' == $theme )
{
// do something
}
return;
}
add_action('switch_theme', 'my_activation_settings');
只是一个想法;我没有测试过。
关于php - WordPress 自定义主题 > 仅在激活时执行 "Setup"代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2566921/