制作插件时,在插件安装时执行一次代码,经常这样写:

register_activation_hook(__FILE__, function () {
    //....代码
});

该函数其实是添加了一个动作钩子:

function register_activation_hook( $file, $callback ) {
    $file = plugin_basename( $file );
    add_action( 'activate_' . $file, $callback );
}

这个钩子的执行顺序是在插件激活之前,可以用以下方式验证:

在 wp-admin/includes/plugin.php 文件大约698行处,有这样一段代码:

if (!$silent) {
    /**
     * Fires before a plugin is activated.
     * If a plugin is silently activated (such as during an update),
     * this hook does not fire.
     * @param string $plugin       Path to the plugin file relative to the plugins directory.
     * @param bool   $network_wide Whether to enable the plugin for all sites in the network
     *                             or just the current site. Multisite only. Default false.
     * @since 2.9.0
     */
    do_action('activate_plugin', $plugin, $network_wide);

    /**
     * Fires as a specific plugin is being activated.
     * This hook is the "activation" hook used internally by register_activation_hook().
     * The dynamic portion of the hook name, `$plugin`, refers to the plugin basename.
     * If a plugin is silently activated (such as during an update), this hook does not fire.
     * @param bool $network_wide Whether to enable the plugin for all sites in the network
     *                           or just the current site. Multisite only. Default false.
     * @since 2.0.0
     */
    do_action("activate_{$plugin}", $network_wide);
}

在 do_action("activate_{$plugin}", $network_wide) 之后添加 exit,插件就无法激活了。说明此时执行我们写的动作钩子,我们的插件还没有激活。