我在functions.php文件中有一些设置代码,用于设置永久链接并添加主题使用的类别。我只想在首次激活主题时运行此代码。代码无需再次运行。但是,通过将其放在functions.php文件中,它会在每次加载网站上的页面时运行。
是否有其他方法可供使用,以便此代码仅在首次激活自定义主题时运行?
答案 0 :(得分: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');
只是一个想法;我还没有测试过。
答案 1 :(得分:1)
另一个要看的是after_switch_theme
它也在 wp-includes / 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');
我认为两种方式都可以解决其他问题:)