How does add_option() function enable action hooks to fire right after actiavtion?

The documentation page says that the hook process performs an instant redirect after it fires. So, in order to do something right after the activation the page suggests using add_option like so,

function my_plugin_activate() {

  add_option( 'Activated_Plugin', 'Plugin-Slug' );

  /* activation code here */
}
register_activation_hook( __FILE__, 'my_plugin_activate' );

function load_plugin() {

    if ( is_admin()  get_option( 'Activated_Plugin' ) == 'Plugin-Slug' ) {

        delete_option( 'Activated_Plugin' );

        /* do stuff once right after activation */
        // example: add_action( 'init', 'my_init_function' );
    }
}
add_action( 'admin_init', 'load_plugin' );

How is this any different from,

function load_plugin()
{
 //some code
}
add_action('admin_init','load_plugin');

Won't load_plugin() function run in the same order in both the cases?

Topic php plugin-development Wordpress

Category Web


The important thing to note is that admin_init runs on every admin page load. So if you put a redirect inside that hook it will redirect every time you try to do something in the admin.

In this code when the plugin is activated an option is saved in the database, Activated_Plugin. The next time admin_init runs this option is checked and if it exists the option is deleted. This means that the option will only exist for one page load. So if you put code inside this check it will only run once, because the next time admin_init runs the database option won't exist anymore.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.