• Resolved cognitions

    (@cognitions)


    I know how to do stuff, but I need to do it only once when a theme is activated.

    In my theme’s functions file, I want to put something that says:

    when this theme is first activated {

    DO THIS STUFF ONCE

    }
    and do no tdo it again.

    I have searched hooks, filters and forums and am stuck.

    Any help appreciated.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Yeah, I had a bit of trouble with this one too. Although functions.php is supposed to act like a plugin, some of the plugin actions ( like the key register_activation_hook) don’t work.

    One workaround I used was to check for a database variable, if it’s not found (which it wouldn’t be if the theme was just installed), then do all your actions, else do nothing. The code was something like:

    $check = get_option('theme_name_activation_check');
    
    if ( $check != "set" ) {
      // DO INITIALISATION STUFF
    
      // Add marker so it doesn't run in future
      add_option('theme_name_activation_check', "set");
    }

    Then, to make sure that it all happens again should the theme be de-activated and re-activated, you can use the theme_switch action.

    function delete_stuff() {
      delete_option('theme_name_activation_check');
    } 
    
    add_action('switch_theme', 'delete_stuff');

    Not pretty, but it works. If anyone has any better suggestions, I would also really love to hear them…

    Note that the switch_theme action is only triggered when you switch away from a theme, not into it…

    Thread Starter cognitions

    (@cognitions)

    I wanted to try everything with your code before replying.

    Please forgive me if this is my fault…but:

    No matter how I code it, the code seems not to distinguish between:

    $check != “set”

    and

    $check = “set”

    And it returns the same whether or not the theme_name_activation_check is in the options database table or not.

    If I could get this solution to work it would be great.

    Any comments would be appreciated.

    Many thanks.

    Apologies, I missed out this important part: You need to wrap the first part of the code I wrote into an action so that it gets loaded. E.g.

    function first_run_options() {
      $check = get_option('theme_name_activation_check');
    
      if ( $check != "set" ) {
        // DO INITIALISATION STUFF
    
        // Add marker so it doesn't run in future
        add_option('theme_name_activation_check', "set");
      }
    
    add_action('wp_head', 'first_run_option');

    Sorry for not making that clearer. This should work now.

    Thread Starter cognitions

    (@cognitions)

    This now works perfectly.

    Thank you so much for following this through!

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘How to do something once when theme is activated’ is closed to new replies.