在WordPress中运行主题激活功能

jam*_*lin 4 php wordpress wordpress-theming

我正在尝试使用钩子在主题激活上设置图像大小,after_setup_theme但它似乎从未真正调用过.为什么?

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' );
Run Code Online (Sandbox Code Playgroud)

相反,我已经做了一个解决方案的工作,但如果有一个钩子它不会感觉最佳:

if ( is_admin() && isset($_GET['activated'] ) && $pagenow == 'themes.php' ) {
    theme_image_size_setup();
}
Run Code Online (Sandbox Code Playgroud)

这有效......但为什么after_setup_theme钩子上没有响应?

jet*_*lej 5

这只会在您的主题从另一个主题切换到TO时运行.这是您可以获得最接近主题激活的内容:

add_action("after_switch_theme", "mytheme_do_something");
Run Code Online (Sandbox Code Playgroud)

或者你可以在你的wp_options表中保存一个选项,并在每个页面加载上检查一个选项,很多人都推荐这个选项,即使它对我来说似乎效率低下:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)