register_activation_hook vs add_action('init&#

2020-08-05 10:07发布

I'm trying to determine why some WordPress plugins use register_activation_hook(__FILE__, 'activate_plugin') while others use the action add_action('init', 'activate_plugin');

标签: php wordpress
3条回答
小情绪 Triste *
2楼-- · 2020-08-05 10:41

A few reasons:

  • register_activation_hook is WP2+, add_action was available to use before that
  • register_activation_hook allows the developer to specify the file the function resides in (although this seems rarely used)
  • for me, register_activation_hook is 'cleaner'

So I'd bet that plugins using add_action date from before version 2 or the developer isn't aware of register_activation_hook

查看更多
可以哭但决不认输i
3楼-- · 2020-08-05 11:01

Hooking an "activate_plugin" function to init looks to either be code done a long time ago, or by someone who doesn't know about register_activation_hook. A third possibility is that despite the function name they want it to run whether or not register_activation_hook is called.

For example, when updating a plugin, the plugin is deactivated and reactivated, but the activate hook is not called. (And it's certainly not called if the plugin is updated via FTP or similar.) So if I were putting in some code that need to run on activate or after an update I might hook it to init.

查看更多
贼婆χ
4楼-- · 2020-08-05 11:03

The two do different things, register_activation_hook is used to register a function which will be called once when the plug-in is activated (on the Wordpress plug-in management page), whereas functions hooked into the init action will be called on every request.

So, common examples would be to use an activation function to create database tables, or set default options for a plug-in and then an init action function to load translated strings.

查看更多
登录 后发表回答