tags:

views:

41

answers:

1

I have some setup code in my functions.php file that sets permalinks and adds categories that are used by the theme. I only want this code to run when the theme is first activated. There is no need for the code to run again. However, by placing it in the functions.php file, it runs each and every time a page on the website is loaded.

Is there an alternative method to use so that this code only runs when the custom theme is first activated?

A: 

In wp-includes/theme.php you’ll find the function switch_theme(). It offers an 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);
}

So you may use this in your functions.php:

function my_activation_settings($theme)
{
    if ( 'Your Theme Name' == $theme )
    {
        // do something
    }
    return;
}
add_action('switch_theme', 'my_activation_settings');

Just an idea; I haven’t tested it.

toscho
Thanks toscho, I appreciate it!
Scott B