The init
and plugins_loaded
hooks are already run before a plugin is activated. That’s why your first code doesn’t work but the second does.
Regarding your third code: there’s no need to run add_action('myplugin_activate' …
inside init
. Not everything needs to be hooked to init
. Just use
add_action('myplugin_activate', function(){
echo 'myplugin is not allowed.';
die;
});
without any init
stuff. Although I probably wouldn’t exactly use die
🙂
Check out the Codex article on register_activation_hook()
which has many valuable examples.