There isn’t yet a WordPress activate theme hook. In the last week, it’s come up twice where WordPress.com Hosting VIP partners wanted some code to run once on theme activation.
It’s not an unusual scenario for our customers to create a new version of a theme, install it separately, and then activate it. Often this also allows reverting to the old version of the theme if something unexpected happens at launch.
In this scenario, it’s often easy to check for the existence of a new option, migrated, or other seed data, but sometimes you want to do something like:
global $pagenow;
if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) ) {
// When theme is activated this code runs.
// Still be defensive if you need to be, and check if
// your baby is already born
}
Since WordPress 2.9.2, rather than stuffing a ton of custom functions into an active theme, I’ve started putting everything into a custom plugin, and then using the
register_theme_directoryto tell WordPress where their custom theme lives.This allows the theme to be a bit more modular than if everything was automatically included in the themes functions file. In situations where there are multiple sites with similar, but slightly different themes, this also makes it much easier to have central CSS, JS, and Image directories that all of the parent/child themes can use, which helps in little ways like not having to download the same image across multiple themes, etc…
The reason why this applies here? If you do it this way, you automatically get the
register_activation_hookandregister_deactivation_hookfunctions with your plugin. This way when a new version of the ‘theme’ rolls out, you get real activation and deactivation methods too.JJJ thanks for sharing this very interesting approach. Is there an example of this in action I can grab from wordpress.org/extend ?
BuddyPress is a great example of something similar to this. If you needed me to I could whip up a more simple example for you quick.
Thanks JJJ. No need currently. I’ll keep my eyes open for this style.
You can also get a deactivation hook by catching the user switching the theme, For example, i used this in some code a long time ago:
add_action('switch_theme', 'theme_deactivate');
function theme_deactivate(){
delete_option('my_options_that_dont_matter');
}
What about the switch_themes action? There’s no action when widgets are updated either and I’m thinking of checking for the update POSTs to the widgets page for wp-super-cache.
As DD32 suggests above, the problem with
switch_themesis that it only fires on theme deactivate, not activate.