2010-04-02 28 views
0

我在我的functions.php文件中設置了一些設置代碼,用於設置永久鏈接並添加主題使用的類別。我只希望這個代碼在主題首次激活時運行。代碼不需要再次運行。但是,通過將其放置在functions.php文件中,它每次在網站上加載頁面時都會運行。WordPress自定義主題>僅在激活時執行「設置」代碼?

是否有其他方法使用,以便此代碼僅在自定義主題首次激活時運行?

回答

3

wp-includes/theme.php你會發現功能switch_theme()。它提供了一個行動鉤:

/** 
* 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'); 

只是一個想法;我沒有測試過它。

+0

謝謝toscho,我欣賞它! – 2010-04-02 21:18:50

1

另一種方式來看待會after_switch_theme它也是WP-包括/ theme.php

這似乎是在check_theme_switched

/** 
    * Checks if a theme has been changed and runs 'after_switch_theme' hook on the next WP load 
    * 
    * @since 3.3.0 
    */ 
    function check_theme_switched() { 
      if ($stylesheet = get_option('theme_switched')) { 
        $old_theme = wp_get_theme($stylesheet); 

        // Prevent retrieve_widgets() from running since Customizer already called it up front 
        if (get_option('theme_switched_via_customizer')) { 
          remove_action('after_switch_theme', '_wp_sidebars_changed'); 
          update_option('theme_switched_via_customizer', false); 
        } 

        if ($old_theme->exists()) { 
          /** 
          * Fires on the first WP load after a theme switch if the old theme still exists. 
          * 
          * This action fires multiple times and the parameters differs 
          * according to the context, if the old theme exists or not. 
          * If the old theme is missing, the parameter will be the slug 
          * of the old theme. 
          * 
          * @since 3.3.0 
          * 
          * @param string $old_name Old theme name. 
          * @param WP_Theme $old_theme WP_Theme instance of the old theme. 
          */ 
          do_action('after_switch_theme', $old_theme->get('Name'), $old_theme); 
        } else { 
          /** This action is documented in wp-includes/theme.php */ 
          do_action('after_switch_theme', $stylesheet); 
        } 
        flush_rewrite_rules(); 

        update_option('theme_switched', false); 
      } 
    }` 

add_action('after_switch_theme', 'my_activation_settings');

鉤運行我認爲這兩種方式工作只是別的東西來看看:)

相關問題