【问题标题】:Run function on theme activation in WordPress在 WordPress 中运行主题激活功能
【发布时间】:2012-12-03 13:39:01
【问题描述】:

我正在尝试使用挂钩 after_setup_theme 在主题激活时设置图像大小,但它似乎从未真正调用过它。为什么?

if( !function_exists('theme_image_size_setup') )
{
    function theme_image_size_setup()
    {
        //Setting thumbnail size
        update_option('thumbnail_size_w', 200);
        update_option('thumbnail_size_h', 200);
        update_option('thumbnail_crop', 1);
        //Setting medium size
        update_option('medium_size_w', 400);
        update_option('medium_size_h', 9999);
        //Setting large size
        update_option('large_size_w', 800);
        update_option('large_size_h', 9999);
    }
}
add_action( 'after_setup_theme ', 'theme_image_size_setup' );

相反,我做了一个解决方案,但如果有一个钩子,它不会感觉最佳:

if ( is_admin() && isset($_GET['activated'] ) && $pagenow == 'themes.php' ) {
    theme_image_size_setup();
}

这行得通...但是为什么after_setup_theme 钩子上没有响应?

【问题讨论】:

    标签: php wordpress wordpress-theming


    【解决方案1】:

    这只会在您的主题从另一个主题切换到时运行。这是您最接近主题激活的方式:

    add_action("after_switch_theme", "mytheme_do_something");
    

    或者您可以在 wp_options 表中保存一个选项,并在每次页面加载时检查该选项,尽管对我来说似乎效率低下,但很多人都建议这样做:

    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);
        }
    }
    

    【讨论】:

      【解决方案2】:

      每次加载页面时,after_setup_theme 都会运行。所以它不是更好的解决方案。

      【讨论】:

      • 没有提供更好的解决方案
      【解决方案3】:

      问题可能是您在此字符串'after_setup_theme ' 中有额外的空间。
      试试这样:

      add_action( 'after_setup_theme', 'theme_image_size_setup' );
      

      【讨论】:

      • 哦,多么愚蠢。感谢您的关注。
      • @jamietelin 我已经浪费了好几个小时试图调试这类错误。我恨他们!
      • 这会在每次页面加载时运行,请参阅我的答案以获得更有效的解决方案
      【解决方案4】:

      在 WPMU 环境中使用 WP 3.9,有一个名为 switch_theme 的动作,它被称为你切换主题的一切。

      当调用此操作时,会传递以下 $_GET 参数:action=activate, stylesheet=

      我在 mu-plugins/theme-activation-hook.php 中创建了一个新文件

      add_action('switch_theme','rms_switch_theme');
      function rms_switch_theme($new_name, $new_theme='') {
          if (isset($_GET['action']) && $_GET['action'] == 'activate') {
              if (isset($_GET['stylesheet']) && $_GET['stylesheet'] == 'rms') {
                  // perform the theme switch processing,
                  // I echo the globals and immediately exit as WP will do redirects 
                  // and will not see any debugging output on the browser.
                  echo '<pre>'; print_r($GLOBALS); echo '</pre>'; exit;
              }
          } 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-06
        • 1970-01-01
        • 1970-01-01
        • 2011-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多