UPDATE (3 August 2012): In version 3.3.0 wordpress core provided direct activation/deactivation hook for themes (see the new usage below). (thanks to jacobsnyder for telling me about it)
NOTE: The old approach will still work, so you don’t need to change your existing code if you were using the old approach.
Activation hook:
Code:
<?php function myactivationfunction($oldname, $oldtheme=false) { } add_action("after_switch_theme", "myactivationfunction", 10 , 2); |
Explanation:
We write a function ‘myactivationfunction’ and attach it to “after_switch_theme” hook. (This goes in your functions.php file)
Detailed Explanation (not necessary to use):
When theme is deactivated, wordpress core switches the theme in switch_theme function (wp-includes/theme.php @line 649). This function calls “switch_theme” hook (which we will use as deactivation hook), and adds an option “theme_switched”.
check_theme_switched() function is attached to “init” hook on every page request [add_action( 'init', 'check_theme_switched', 99 ); is attached at wp-includes/default-filters.php (@line 214)]. Its job is to check if “theme_switched” option exists and if it exists then it does “after_switch_theme” action. After performing that action it deletes that option “theme_switched”.
It’s similar to the approach we were taking.
Deactivation hook:
Code:
<?php function mydeactivationfunction($newname, $newtheme) { } add_action("switch_theme", "mydeactivationfunction", 10 , 2); |
Explanation:
We write a function ‘mydeactivationfunction’ and attach it to “switch_theme” hook. (This goes in your functions.php file)
Detailed Explanation (not necessary to use):
When admin activates a new theme, switch_theme function is called at wp-includes/theme.php (@line 23). This function calls “switch_theme” hook which we use as deactivation hook.
For wordpress version < 3.3.0
When you develop plugin you can use register_activation_hook and register_deactivation_hook functions to add your functions which will be called when plugin is being activated or deactivated. They are very useful functions as often plugin developer has to set the environment for plugin to work.
No such hooks exist for wordpress themes. If you are a theme developer and you need to run some code when theme gets activated then you have to rely on unreliable methods like this:
if ( is_admin() && isset($_GET['activated'] ) && $pagenow == 'themes.php' ) { // your code here } |
This method is pretty unreliable as after activating a theme admin can refresh that page and if that happens then your activation code will run twice.
And there is no method at all to run some code on theme deactivation. Now as themes are evolving rapidly this poses one serious limitation.
As wordpress 3.0.4 came out I once again thought of searching for any such method, but they haven’t provided any such hooks for themes yet.
I have developed theme activation/deactivation hooks and I think that it is 100% reliable.
Download and include this php file in your theme code. Register hooks and that’s all. File has usage example at top. Let me know what you guys think.
/** * Provides activation/deactivation hook for wordpress theme. * * Usage: * ---------------------------------------------- * Include this file before this line. * ---------------------------------------------- * function my_theme_activate() { * // code to execute on theme activation * } * wp_register_theme_activation_hook('mytheme', 'my_theme_activate'); * * function my_theme_deactivate() { * // code to execute on theme deactivation * } * wp_register_theme_deactivation_hook('mytheme', 'my_theme_deactivate'); * ---------------------------------------------- * * @author Krishna Kant Sharma (http://www.krishnakantsharma.com) */ /** * * @desc registers a theme activation hook * @param string $code : Code of the theme. This can be the base folder of your theme. Eg if your theme is in folder 'mytheme' then code will be 'mytheme' * @param callback $function : Function to call when theme gets activated. */ 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); } } /** * @desc registers deactivation hook * @param string $code : Code of the theme. This must match the value you provided in wp_register_theme_activation_hook function as $code * @param callback $function : Function to call when theme gets deactivated. */ function wp_register_theme_deactivation_hook($code, $function) { // store function in code specific global $GLOBALS["wp_register_theme_deactivation_hook_function" . $code]=$function; // create a runtime function which will delete the option set while activation of this theme and will call deactivation function provided in $function $fn=create_function('$theme', ' call_user_func($GLOBALS["wp_register_theme_deactivation_hook_function' . $code . '"]); delete_option("theme_is_activated_' . $code. '");'); // add above created function to switch_theme action hook. This hook gets called when admin changes the theme. // Due to wordpress core implementation this hook can only be received by currently active theme (which is going to be deactivated as admin has chosen another one. // Your theme can perceive this hook as a deactivation hook.) add_action("switch_theme", $fn); } |

As you’ve added at the top of the article, WP 3.3 now has this type of thing built-in. However a lot of my clients are still running 3.0 or even 2.9 and don’t want to upgrade for whatever reason. So I think it’s best to use a hybrid approach. You can write a single activation function and then check the WP version and if it’s before 3.3 use Krishna’s excellent hook, but if your theme is being installed on 3.3 or higher it will use the new core hook. Like this:
if(version_compare( get_bloginfo('version'), '3.3', '>=' )) {
add_action('after_switch_theme','mytheme_activation_function');
}
else {
include_once('krisha_hooks.php');
wp_register_theme_activation_hook('mytheme', 'mytheme_activation_function');
}
True. We can also update the hooks file itself.
function wp_register_theme_activation_hook($code, $function) {if(version_compare( get_bloginfo('version'), '3.3', '>=' )) {
add_action('after_switch_theme',$function);
}
else {
$optionKey="theme_is_activated_" . $code;
if(!get_option($optionKey)) {
call_user_func($function);
update_option($optionKey , 1);
}
}
}
function wp_register_theme_deactivation_hook($code, $function) {
if(version_compare( get_bloginfo('version'), '3.3', '>=' )) {
add_action('switch_theme',$function);
}
else {
// store function in code specific global
$GLOBALS["wp_register_theme_deactivation_hook_function" . $code]=$function;
// create a runtime function which will delete the option set while activation of this theme and will call deactivation function provided in $function
$fn=create_function('$theme', ' call_user_func($GLOBALS["wp_register_theme_deactivation_hook_function' . $code . '"]); delete_option("theme_is_activated_' . $code. '");');
// add above created function to switch_theme action hook. This hook gets called when admin changes the theme.
// Due to wordpress core implementation this hook can only be received by currently active theme (which is going to be deactivated as admin has chosen another one.
// Your theme can perceive this hook as a deactivation hook.)
add_action("switch_theme", $fn);
}
}
Please also note that old approach will still work (in version > 3.3 ).
Nice update! This is really the definitive source at this point.
Deactivation doesn’t work for me, when I put it in the theme functions. Not sure if it is because it is in the theme functions, and doesn’t get a chance to be called, or if it is just my setup.
Can you provide the code (how you are using it)? You can obviously use this new approach. I am just curious why it’s not working for you.
@Krishna
I put an example in pastebin:
http://pastebin.com/yi50kzh8
When I activate, it works a charm, but on deactivation, nothing I have tried has worked. I have a very specialized theme that creates new roles and deletes some existing roles, and I wanted to be able to restore roles and settings upon deactivation.
Thanks again for the info. Was very useful in getting me on the right track.
This is the new version of activation/deactivation code that you have pasted there. I was actually asking for the older one, as you said you were having problem with that.
I have again tested both versions and they are working fine.
May be there is something wrong with the function you are trying to hook. Try something simpler.
Add a function which just creates an option on activation and delete that option on deactivation: update_option(“thtestact”, 1) , delete_option(“thtestact”).
Check if your registered function are being loaded. You might have been registering/defining those functions in some unreachable code/hook. Logging might help.
I also advise you to enable debugging on in wp-config.php file by updating define(‘WP_DEBUG’, false); to define(‘WP_DEBUG’, true);
Thanks
Also. Have you tried it in the theme functions? Seems like it would work in a plugin, but since theme is getting deactivated, it might have a chance to actually know it is getting deactivated. The call might come after the theme is already gone.
And yes, I have tried these functions in theme code. I have never used it in a plugin, didn’t make any sense to do that, yet.
Implementation of switch_theme and after_switch_theme is different. switch_theme is triggered when older theme is still in place.
This website has got some really helpful info on it. Cheers for helping me.
Is there an official approach already, or this is the only current available solution? There is a ticked but I don’t think they have it working or I am wrong?
http://core.trac.wordpress.org/ticket/7795
I don’t think that there are official activation/deactivation hooks for themes yet. This is still the only reliable solution.
Someone in the link you provided mentioned:
Theme activation hook: ‘after_switch_theme’
Theme de-activation hook: ‘switch_theme’
This solution already uses ‘switch_theme’ hook.
I haven’t checked ‘after_switch_theme’ hook myself though. You can check it out if you want.
Don’t get me wrong your solution is nice indeed but it has one downfall – adds additional 1 query on all page loads.
I am glad that you are thinking of optimizing your code to that level
. But I wouldn’t worry too much about it.
This option ["theme_is_activated_" . $code] is an “autoload” type option. All such options are loaded in single query (single SELECT statement) in “wp_load_alloptions” function. There is no additional query.
Can i add this to my Parent Theme (Our Theme framework) and hook when i activation my child theme? I tried but it’s not work.
Hi,
Can you provide the code you are using?
Krishna
Didnt work for me.
First the instructions are blurry, which theme-function file needs to have the activation and deactivation code (?) the new one which should be activated or the current one which already ?
Tried both versions, added your php file in both themes and tested first with current theme and later with theme that should be activated but none of the ways worked out for me.
Of course this doesnt mean it doesnt work, maybe it doesnt work as i expect it to.
What im looking for is a piece of code that activates another theme, in this case i need that with is_admin().
thanks for a nice tutorial, really love this post, this solve my problem
newbie here, you’re my savior thanks a lot krish
is there any way to active them outside of wp_admin … like many webs are providing live demo of there wp themes.????
activation work fine, but deactivation not work .
+1 Deactivation doesn’t work. Maybe it is the theme activation changes in 3.4. Also you can use this hook: “after_switch_theme”, for activation. So without the deactivation, I don’t think there is a need for these functions anymore.
Nice work though!
Thanks Jake for telling me about it. I have checked and you are right; I have updated the above post. Deactivation hook was working though.
Can you provide the code you are using?
This is exactly what I’m looking for, but I don’t understand your usage instructions at all. How does putting this php file in my theme folder do anything? Do I have to include this code in functions.php? And how do I actually activate these hooks?
Can you please give me an actual example since I’m not tech-savvy enough to understand your instructions. Thanks!
Instructions:
1) Download php file from above post. Place it in your theme folder as “theme_activation_hook.php”
2) Lets say your theme folder is “mytheme”. In your functions.php file place this code:
require_once “theme_activation_hook.php”;
function my_theme_activate() {
// code to execute on theme activation
}
wp_register_theme_activation_hook(‘mytheme’, ‘my_theme_activate’);
function my_theme_deactivate() {
// code to execute on theme deactivation
}
wp_register_theme_deactivation_hook(‘mytheme’, ‘my_theme_deactivate’);
That’s all. I hope you understand it now. Let me know if you have any doubts.
How to create category when I activate plugin and when I deactivate plugin then category will automatically deleted. Is there any function please tell me.
Regards
Manish
Check out these functions:
register_activation_hook
wp_insert_category
register_deactivation_hook
wp_delete_category
Nice, that enabled me to do it!
Thanks, Krishna. This seems like it could work.
What others are saying about this article: