Search code examples
wordpresswordpress-hook

admin_init hook not working as expected (cannot write to log, cannot add actions)


I'm trying to add some actions once after plugin activation. I found out that this should be done more or less like so:

register_activation_hook( __FILE__, 'activation_function' );
add_action('admin_init', 'after_activation_function');


function activation_function(){
   add_option( 'activated_plugin_xyz', 'plugin xyz activated' );  //option is added to database
}

function after_activation_function(){
   if (is_admin() && get_option ('activated_plugin_xyz') == 'plugin xyz activated'){
      //do some things
      wp_schedule_event(time(), 'daily', 'some_cron'); //cron event is added
      add_action('wp_login', 'xyz_login_action'); 
      add_action('some_cron', 'xyz_cron_job');  //cron job is correctly hooked
      //delete_option('activated_plugin_xyz');
   }
    error_log("nothing in debug.log log...");
    echo ("echoing works");
    //wp_die('dying works');
}

function xyz_cron_job(){
    error_log('cron job not logging anything...');  //nothing in log...
}

I can see the cron job in wp crontrol, the function xyz_cron_job is hooked, but when I trigger it manually nothing is written to the log. xyz_login_action also seems not to work. If I do other things in xyz_cron_job they seem to have no effect as well...

after_activation_function is called bcs dying works if I uncomment it. Can anybody help me? It seems to me like I am missing something fundamental...


Solution

  • fixed it:

    actions have to be added outside after_activation_function()

    (I guess actions have to be hooked every time wp loads and if hooking happens in after_activation_function() the hook runs before the action is hooked)

    working code looks like this:

    register_activation_hook( __FILE__, 'activation_function' );
    add_action('admin_init', 'after_activation_function');
    
    //hook outside other functions
    add_action('some_cron', 'xyz_cron_job'); 
    add_action('wp_login', 'xyz_login_action'); 
    
    function activation_function(){
       add_option( 'activated_plugin_xyz', 'plugin xyz activated' );  //option is added to database
    }
    
    function after_activation_function(){
       if (is_admin() && get_option ('activated_plugin_xyz') == 'plugin xyz activated'){
          //do some things
          wp_schedule_event(time(), 'daily', 'some_cron');
          delete_option('activated_plugin_xyz');
       }
    }
    
    function xyz_cron_job(){
       error_log('logging works');
    }