I am trying to register an activation hook for my plugin. The plugin is using classes and the actual activation method is held in a separate admin class. Reading the documentation for register_activation_hook()
it seems like the first parameter $file
should always be the file of the main plugin file:
Path to the main plugin file inside the wp-content/plugins directory. A full path will work.
The two classes are kept in separate files, which looks something like this.
This is the main plugin file:
<?php
/* my-plugin.php */
include_once(plugin_dir_path(__FILE__) . '/admin/my-plugin-admin.php');
register_activation_hook(__FILE__, array('MyPluginAdmin', 'activate'));
class MyPlugin {
}
While this is the admin part, which also contains the activation routine:
<?php
/* my-plugin-admin.php */
class MyPluginAdmin {
public static function activate() {
// This method is called in both cases,
// but in the first example a php warning is generated
}
}
My problem is that static activate
method is actually triggered on activation, but I still get a php warning which looks like this:
PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'MyPluginAdmin' not found in /var/www/html/wp/wp-includes/class-wp-hook.php on line 287
PHP Stack trace:
1. {main}() /var/www/html/wp/wp-admin/plugins.php:0
2. activate_plugin($plugin = 'my-plugin/my-plugin.php', $redirect = 'http://localhost/wp/wp-admin/plugins.php?error=true&plugin=my-plugin%2Fmy-plugin.php', $network_wide = FALSE, $silent = *uninitialized*) /var/www/html/wp/wp-admin/plugins.php:43
3. do_action($tag = 'activate_my-plugin/my-plugin.php', $arg = FALSE) /var/www/html/wp/wp-admin/includes/plugin.php:586
4. WP_Hook->do_action($args = array (0 => FALSE)) /var/www/html/wp/wp-includes/plugin.php:453
5. WP_Hook->apply_filters($value = '', $args = array (0 => FALSE)) /var/www/html/wp/wp-includes/class-wp-hook.php:311
6. call_user_func_array:{/var/www/html/wp/wp-includes/class-wp-hook.php:287}(array (0 => 'MyPluginAdmin', 1 => 'activate'), array (0 => FALSE)) /var/www/html/wp/wp-includes/class-wp-hook.php:287
If I change the call to register_activation_hook()
into:
register_activation_hook(plugin_dir_path(__FILE__) . '/admin/my-plugin-admin.php', array('MyPluginAdmin', 'activate'));
Then the warning message disappears.
So, my question is what is the correct way to use register_activation_hook()
and why does it work in both above cases although it throws a warning in the first scenario?