If you’re developing a WordPress plugin, any initial, one-time setup work your plugin needs is done through a call to
register_activation_hook() (such as registering settings, or creating a database table). Debugging problems with code you call through this hook is notoriously difficult. I think I’ve pulled my hair out over each one of the many things that can go wrong, so I thought I’d share my hard-earned solutions (these all apply to the current version of WordPress, 3.0.4):
- You get a “Cannot redeclare” error when activating your plugin from the plugin menu: this may tempt you to put a
if function_exists()wrapper around your function (or
if class_exists()around your class). But don’t waste your time – all it really means is that there was an error of some kind. Any kind of logic error within your function (such as an incorrect number of arguments to a function call) will result in this error being displayed. Don’t be fooled.
- You try using
trigger_error()instead. This will force your message to be displayed in the plugin activation status box.
- It says “plugin activated” after you activate from the plugin menu, but nothing actually happened: this typically means there’s something wrong with your arguments to
register_activation_hook, and it just fails silently. The first argument must be the path to your main plugin file (i.e. the file with the plugin comments at the top –
__FILE__will do fine), which is where your activation function must be. The existence of this argument is deceptive, as it suggests you could put the function in another file (you could, I suppose, put your call to
register_activation_hookin another file, and then put your callback function in the main file, but I can’t think of a good reason to do that). The second argument is the function name – if you want to get fancy, it’s fine to use callback pseudo-types.
- You’re having trouble using a global variable: this limitation is actually documented.
Two general guidelines I recommend are:
- Temporarily put an “activate” button on your plugin’s settings page, and have it call your activation method. This will allow you to separate any problems with your activation function from any problems that may exist in how you’re calling it through
register_activation_hook. This is a good way to expose errors that are otherwise hidden behind the “cannot redeclare” error.
- Write unit tests and do test-driven development! This will give you a way to verify the functionality of your code as you work on it, and will let you know immediately if you break anything. I’ll have an upcoming post on how to use SimpleTest with WordPress.