当我在主插件文件 (plugin.php) 的顶部安排一个事件时,cron 被添加到 wp_options cron
选项。
wp_schedule_event( time() + 10, 'hourly', 'this_is_my_action' );
这很好用,它添加了新的 cron。但是,当我尝试在插件类中的激活函数中使用相同的函数时,它不起作用。
在 plugin.php 里面我有:
$plugin = new My_Plugin(__FILE__);
$plugin->initialize();
在 My_Plugin 类中我有:
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){
/*...*/
}
}
当我激活插件时,日志被写入,但 cron 没有被添加到 wordpress 数据库。有什么想法吗?
最佳答案
您需要定义您在预定事件中注册的操作:
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
}
}
关于php - wp_schedule_event()在类激活函数中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17537776/