开发者

register_activation_hook vs add_action('init')

I'm trying to determine why some WordPress pl开发者_如何学Cugins use register_activation_hook(__FILE__, 'activate_plugin') while others use the action add_action('init', 'activate_plugin');


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜