Wp_schedule_event () does not work inside class activation function

When I schedule an event at the top of the main plugin file (plugin.php), cron is added to the wp_options cron parameter.

wp_schedule_event( time() + 10, 'hourly', 'this_is_my_action' );

This works great, adds a new cron. But, when I try to use the same function in my activation function inside the plugin class, it does not work.

Inside plugin.php I have:

 $plugin = new My_Plugin(__FILE__); $plugin->initialize(); 

Inside the My_Plugin class, I have:

 class My_Plugin{ function __construct($plugin_file){ $this->plugin_file = $plugin_file; } function initialize(){ register_activation_hook( $this->plugin_file, array( $this, 'register_activation_hook' ) ); } function register_activation_hook() { $this->log( 'Scheduling action.' ); wp_schedule_event( time() + 10, 'hourly', 'this_is_my_action' ); } function log($message){ /*...*/ } } 

The log is logged when I activate the plugin, but cron is not added to the wordpress database. Any ideas why?

+6
source share
2 answers

You need to determine the action that you recorded in the planned event:

 class My_Plugin{ function __construct($plugin_file){ $this->plugin_file = $plugin_file; } function initialize(){ register_activation_hook( $this->plugin_file, array( $this, 'register_activation_hook' ) ); add_action( 'this_is_my_action', array( $this, 'do_it' ); } function register_activation_hook() { if ( !wp_next_scheduled( 'this_is_my_action' ) ) { $this->log( 'Scheduling action.' ); wp_schedule_event( time() + 10, 'hourly', 'this_is_my_action' ); } } function this_is_my_action(){ //do } function log($message){ } function do_it() { // This is your scheduled event } } 
+2
source

Try the following:

 class My_Plugin{ function __construct($plugin_file){ $this->plugin_file = $plugin_file; } function initialize(){ register_activation_hook( $this->plugin_file, array( $this, 'register_activation_hook' ) ); } function register_activation_hook() { $this->log( 'Scheduling action.' ); wp_schedule_event( time() + 10, 'hourly', array( $this,'this_is_my_action' )); } function this_is_my_action(){ //do } function log($message){ } } 

You need to add array($this,'name_function') to the schedule.

-1
source

Source: https://habr.com/ru/post/948984/


All Articles