php - WordPress 自定义主题 > 仅在激活时执行 "Setup"代码?

标签 php wordpress

我的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/

相关文章:

PHP - 执行选择查询并循环结果

php - 如何从 CSS 列表样式 :decimal 中删除点 '.'

css - 为什么我的 CSS 规则无意中改变了多项内容?

wordpress - 如何将文本格式化为看起来像 wordpress 中的代码(如 stackoverflow {} 工具)?

wordpress - 在文件夹 blog 的同一域中安装 Wordpress 和 Laravel

php - 在 wordpress 中的特定帖子类型下插入值之前,我是否需要注册帖子类型?

php - 如何在 Codeigniter 上创建 URL 和阅读?

javascript - PHP/Javascript 变量传递——意想不到的结果

php - 查询类似 Facebook 的新闻源的数据

php - 如何在 WooCommerce 中通过产品 ID 订购相关产品?