register_activation_hook vs add_action(‘init’)

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');

Related posts

Leave a Reply

3 comments

  1. 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.

  2. 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

  3. 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.