I am currently working on developing a plugin, and as such am running apache, php, mysql, etc on my local machine. To make my life easier, I tend to remove the wp-content/plugins directory and replace it with a ‘plugins’ symlink that points to a folder with all of the plugins I generally use in WordPress. I hadn’t ever noticed any issues with this until today, when I was attempting to setup a function to be called on activation with the register_activation_hook() function. Here is how I was trying to implement this, which is the way that is suggested in the codex.
<?php register_activation_hook( __FILE__, 'plugin_activation' ); function plugin_activation() { //do the activation stuff here }
Try this is any WordPress install that doesn’t use symlinks and it will probably work as expected, but when the plugins directory is actually a symlink, it doesn’t work, and this is why; In php, __FILE__ returns the path to the current file with symlinks resolved.
The following is what __FILE__ was returning
/Users/chris/git/myplugin/myplugin.php
WordPress was expecting something more along the lines of this
/Users/chris/domains/wordpress.local/html/wp-content/plugins/myplugin/myplugin.php
When provided with the latter, WordPress is able to remove everything up to and including the plugin directory for the installation, so it would then be left with
myplugin/myplugin.php
Since the path with symlinks resolved doesn’t contain the plugin path as part of it, WordPress gets a bit confused.
To solve this, there are two options. The first would be to just not use symlinks, but I prefer to use them, so I personally chose to do the following.
Instead of using __FILE__ in the register_activation_hook() function, it can be replaced with this
basename(dirname(__FILE__)).'/'.basename(__FILE__)
basename(dirname(__FILE__)) returns the directory that the current file is within, so in this case ‘myplugin’. basename(__FILE__) returns the filename of the current file, which is ‘myplugin.php’. When all is said and done, this ends up returning ‘myplugin/myplugin.php’, which is ultimately what WordPress wants when it is calling the activation function.
For this to work properly, your plugin needs to be in its own directory (within the plugins/ directory) and this should be called from the main plugin file.