I’m curious if there is a known issue with WordPress or PHP where the environment may degrade to a point where WordPress simply ignores calls to register_activation_hook(). I was pulling my hair out for an hour on my local environment running MAMP when I had a coworker test the code on her machine; exact same code works on one machine but not the other.
In this case I simply wanted to append messages to the log file which I’m tailing in real-time.
error_log("Plugin code is being processed");
register_activation_hook( __FILE__, 'myplugin_activate' );
function myplugin_activate()
{
error_log("Attempting to activate");
die("Should not activate");
}
The output on my machine running MAMP and clicking on the “Activate” link under my plugin:
[22-Sep-2011 22:37:16] Plugin code is being processed
[22-Sep-2011 22:37:16] Plugin code is being processed
I feel a bit dense for not noticing this sooner, but I finally realized that my plugins directory on my computer is a symbolic link to another location as pointed out by Kunal Bhalla in symlinks with WP plugins. Since
__FILE__
resolves symbolic linksregister_activation_hook()
is attempting to load a file outside of the WordPress plugins path.If you look at the
register_activation_hook()
function in plugin.php you’ll see the magic seems to happen inplugin_basename()
:Further examination shows that
plugin_basename()
is essentially performing pattern replacement in attempt to turn a system path intomy_plugin/my_plugin.php
; however, sincestr_replace()
is usingWP_PLUGIN_DIR
as the subject, any system path outside of that the WordPress plugin directory will not produce a match to replace against:This method seems a little short-sited, and I’ve found several solutions ranging from defining additional constants in
wp-config.php
to hard-coding the relative path of your plugin. Instead I think a better stop-gap method might be to use the following pattern which pre-defines the pathplugin_basename()
is attempting to extract. This can be used in place of__FILE__
as the first parameter ofregister_activation_hook()
.This method will only work if your plugin has it’s own folder in the
wp-content/plugins
directory and is called from the base plugin file. Both of these conditions seem to be generally in control of the plugin developer, though I’m curious if anyone has some opposing thoughts.Additional Links:
After a little more thought, I think using a resolved path lookup might be safer:
I have used this method: insert the following code in the plugin. THen activate it.
after activation, then open yoursite.com/wp-content/plugins/error_activation.html to see what errors happened.