WordPress Custom Theme> Выполнить код «Настройка» только при активации? - PullRequest
1 голос
/ 02 апреля 2010

В моем файле functions.php есть некоторый установочный код, который устанавливает постоянные ссылки и добавляет категории, используемые темой. Я хочу, чтобы этот код запускался только при первой активации темы. Нет необходимости, чтобы код запускался снова. Однако, поместив его в файл functions.php, он запускается каждый раз при загрузке страницы на веб-сайте.

Есть ли альтернативный метод для использования, чтобы этот код запускался только при первой активации пользовательской темы?

Ответы [ 2 ]

3 голосов
/ 02 апреля 2010

В 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 голос
/ 10 декабря 2015

Еще один вариант, на который стоит обратить внимание: 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');

Я думаю, что оба способа работают только на что-то еще, чтобы разобраться:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...