Correct way to use register_activation_hook

Hi I am developing a plugin and got stuck at one point. I have tried exploring different forums as well as WordPress codex but its not 100% clear. Can anyone help me understand how register_activation_hook actually works.

I have the following code that does not work:

register_activation_hook(__FILE__, 'plugin_activation_fn'  );
      function plugin_activation_fn(){
      define('PLUGIN_DIR', plugin_dir_path( __FILE__ ));
      require_once PLUGIN_DIR . 'includes/contact.php';
}

But if I move that code outside of register_activation_hook function then it works fine

define('PLUGIN_DIR', plugin_dir_path( __FILE__ ));
require_once PLUGIN_DIR . 'options.php';
require_once PLUGIN_DIR . 'includes/contactone.php';

contact.php contains the following code:

if (!empty($_GET['email']) && !empty($_GET['token'])) {
    add_action('init', 'my_test_fn', 0);
}
function my_test_fn(){
    echo'test';
}

What am I doing wrong? Please help. thanks

1 Answer
1

This quotation from The Codex clearly states what does this function do:

The register_activation_hook function registers a plugin function to
be run when the plugin is activated.

This means, this function works similar as a class’s __construct() method. You can use it to set initial options, update database, and more. It doesn’t run every time the core is loaded, it only runs when you click the Activate button of a plugin in the plugins list.

Leave a Comment