2

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

2

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.

3
  • thanks for the quick reply. That makes sense. So If I am understanding it correctly, I should not include files in that hook and only use that for setting defaults, saving values to database etc. correct? What if I have to use register_nav_menus?
    – bakar
    Feb 21, 2018 at 19:05
  • 1
    You are correct. This will only run once, so it's good for setting options and so, the same way register_uninstall_hook is good for clearing options. You should not include register_nav_menus in this hook, since the nav menus should be registered each time the core is initiated. The name register is a bit misleading here.
    – Johansson
    Feb 21, 2018 at 21:10
  • Perfect! makes sense now. Thanks for all your help.
    – bakar
    Feb 21, 2018 at 21:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.