If your included file is using __FILE__
to register, its value will lead to the file in its sub-folder, but you need it to lead to the main plugin file. So if you pass the right path in the included file by not using __FILE__
then the activation hook can execute normally.
You cannot use plugin_dir_path()
for the same reason. Maybe something likeWP_PLUGIN_DIR . '/my-plugin/my-plugin.php'
@bcworkz I think I tried what you said, but that didn’t work either. Here’s the setup:
my-plugin
|-main.php
|-activate-deactivate.php
// main.php
if (is_admin()) {
// I tried both of these with the same result
require_once plugin_dir_path(__FILE__) . 'activate-deactivate.php';
// or
require_once WP_PLUGIN_DIR . '/my-plugin/activate-deactivate.php';
}
// activate-deactivate.php
function my_plugin_on_activation()
{
if (!current_user_can('activate_plugins')) {
return;
}
$plugin = isset($_REQUEST['plugin']) ? $_REQUEST['plugin'] : '';
check_admin_referer("activate-plugin_{$plugin}");
// other stuff that should happen...
}
register_activation_hook(__FILE__, 'my_plugin_on_activation');
function my_plugin_on_deactivation()
{
if (!current_user_can('activate_plugins')) {
return;
}
$plugin = isset($_REQUEST['plugin']) ? $_REQUEST['plugin'] : '';
check_admin_referer("deactivate-plugin_{$plugin}");
// other stuff that should happen...
}
register_deactivation_hook(__FILE__, 'my_plugin_on_deactivation');
Again, these functions work from within main.php, but not when placed in their own file.
OK, but you’re still using __FILE__
in activate-deactivate.php. That’s the one not returning the path you need. Are you saying you tried an alternative there and it didn’t work? If so, perhaps something else is at play, but use of __FILE__
in that context is still incorrect.
@bcworkz Thanks, I understand what you meant now, and it is working. Here are my new files:
// main.php
if (is_admin()) {
require_once plugin_dir_path(__FILE__) . 'activate-deactivate.php';
}
// activate-deactivate.php
function my_plugin_on_activation()
{
if (!current_user_can('activate_plugins')) {
return;
}
$plugin = isset($_REQUEST['plugin']) ? $_REQUEST['plugin'] : '';
check_admin_referer("activate-plugin_{$plugin}");
// other stuff that should happen...
}
register_activation_hook(WP_PLUGIN_DIR . '/my-plugin/main.php', 'my_plugin_on_activation');
function my_plugin_on_deactivation()
{
if (!current_user_can('activate_plugins')) {
return;
}
$plugin = isset($_REQUEST['plugin']) ? $_REQUEST['plugin'] : '';
check_admin_referer("deactivate-plugin_{$plugin}");
// other stuff that should happen...
}
register_deactivation_hook(WP_PLUGIN_DIR . '/my-plugin/main.php', 'my_plugin_on_deactivation');