Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

like image 360
jamietelin Avatar asked Dec 26 '22 13:12

jamietelin


2 Answers

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);
    }
}
like image 116
jetlej Avatar answered Jan 08 '23 19:01

jetlej


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' );
like image 43
ttkalec Avatar answered Jan 08 '23 19:01

ttkalec