I'm testing the plugin activation detection because something went wrong in my plugin. I discovered the problem, but didn't understand it:
I'm trying to check for plugins activation (others and my own) but inside an WordPress hook (init
, for instance)
In the first example i will listen to the "Hello Dolly" plugin activation:
add_action('init', function(){
register_activation_hook('hello.php', function(){
echo 'Hello was activated.';
});
do_action('wordpress_initialized');
});
add_action('wordpress_initialized', function(){
register_activation_hook('hello.php', function(){
echo 'Hello is not allowed.';
die;
});
});
What i'm doing is:
- listening to the
init
hook - Inside it, listening to the
hello.php
plugin activation to say it was activated. - Inside the init hook, triggering an custom hook to say wordpress is loaded
- Outside, i wait for this another custom hook and then listen to the hello activation
- When activated, i block the activation saying it's not allowed.
This is an example, and it works, when the plugin i'm listening is another plugin.
The problem: If i apply this code to listen MY plugin, it will not work. (content below is inside myplugin.php
)
add_action('init', function(){
register_activation_hook('myplugin.php', function(){
echo 'myplugin was activated.';
});
do_action('wordpress_initialized');
});
add_action('wordpress_initialized', function(){
register_activation_hook('myplugin.php', function(){
echo 'myplugin is not allowed.';
die;
});
});
And this happens because, i wait until the init hook to register the activation hook... If i register the activation hook outside any hook, it will work.
But there is more.
If i trigger an custom action inside the activation hook, this action can be listen.
register_activation_hook('myplugin.php', function(){
echo 'myplugin was activated.';
do_action('myplugin_activate');
});
add_action('myplugin_activate', function(){
echo 'myplugin is not allowed.';
die;
});
So there is the problem and there is the solution, but what i don't know is WHY, why i can listen to other plugins activation, but can't listen to my own this way? It's because the activation process? I read about this in the docs and an redirection happens, how this affect the working flow?
---EDIT---
The last example isn't exactly an solution. What i need is add an listener to my own plugin inside the init hook like this:
add_action('init', function (){
add_action('myplugin_activate', function(){
echo 'myplugin is not allowed.';
die;
});
});