Run function on theme activation in WordPress

I am trying to setup image sizes on theme activation using the hook after_setup_theme but it dosent seems like it is never really called. Why?

if( !function_exists('theme_image_size_setup') )
{
    function theme_image_size_setup()
    {
        //Setting thumbnail size
        update_option('thumbnail_size_w', 200);
        update_option('thumbnail_size_h', 200);
        update_option('thumbnail_crop', 1);
        //Setting medium size
        update_option('medium_size_w', 400);
        update_option('medium_size_h', 9999);
        //Setting large size
        update_option('large_size_w', 800);
        update_option('large_size_h', 9999);
    }
}
add_action( 'after_setup_theme ', 'theme_image_size_setup' );

Instead I have doing a work around solution, but it dosn’t feel optimal if there is a hook:

Read More
if ( is_admin() && isset($_GET['activated'] ) && $pagenow == 'themes.php' ) {
    theme_image_size_setup();
}

This works… but why is there no respons on the after_setup_theme hook?

Related posts

Leave a Reply

4 comments

  1. This will only run when your theme has been switch TO from another theme. It’s the closest you can get to theme activation:

    add_action("after_switch_theme", "mytheme_do_something");
    

    Or you can save an option in your wp_options table and check for that on each pageload, which a lot of people recommend even though it seems inefficient to me:

    function wp_register_theme_activation_hook($code, $function) {  
        $optionKey="theme_is_activated_" . $code;
        if(!get_option($optionKey)) {
            call_user_func($function);
            update_option($optionKey , 1);
        }
    }
    
  2. Maybe the problem could be that you have additional space inside this string'after_setup_theme '.
    Try it like this:

    add_action( 'after_setup_theme', 'theme_image_size_setup' );
    
  3. Using WP 3.9 in a WPMU environment, there is an action called switch_theme which is called everything you switch a theme.

    when this action is invoked the following $_GET parameters are passed: action=activate, stylesheet=

    I created a new file in mu-plugins/theme-activation-hook.php

    add_action('switch_theme','rms_switch_theme');
    function rms_switch_theme($new_name, $new_theme='') {
        if (isset($_GET['action']) && $_GET['action'] == 'activate') {
            if (isset($_GET['stylesheet']) && $_GET['stylesheet'] == 'rms') {
                // perform the theme switch processing,
                // I echo the globals and immediately exit as WP will do redirects 
                // and will not see any debugging output on the browser.
                echo '<pre>'; print_r($GLOBALS); echo '</pre>'; exit;
            }
        } 
    }