php - wp_schedule_event()在类激活函数中不起作用

标签 php wordpress

当我在主插件文件 (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/

相关文章:

php - 一键更新一列

php - 在 Woocommerce 中以编程方式自定义运费

php - 如何在 Laravel 4 中批量更新

php - 我的 phpmyadmin 页面安装后是空白的

php - 具有多个自定义字段的 wp_query 返回 0 个结果

html - 在 Wordpress 中通过 CSS 将 Logo 居中

javascript - 事件类不显示

php - Symfony Form 未在多对多关联中保存数据

php - 如何不允许在 PHP 中定义子类方法

javascript - 在codeigniter中将数据从javascript传递到php文件