如何在类中使用wp_schedule_single_event()

问题描述 投票:2回答:1

出于某种原因,我无法使用wp_schedule_single_event触发预定事件。

class My_Class
{
    public function __construct ()
    {
        add_action ( 'after_my_event', array ($this, 'schedule_email_send'), 10, 3 );
        add_action ( 'sendanemail', array ($this, 'send_an_email'), 10, 1 );
    }

    // 3rd party action hook (fires successfully)
    public function schedule_email_send ( $arg1, $arg2, $arg3 )
    {
        wp_clear_scheduled_hook ( 'sendanemail'), array ($arg1) );
        wp_schedule_single_event ( time () + 60, 'sendanemail'), array ($arg1) );
    }

    // Cron task (is never fired)
    function send_an_email ( $arg1 )
    {
        $got_here = true;        // Breakpoint set

        ... code that sends an email.
    {
}

使用上面的代码,第三方WP插件成功触发after_my_event钩子并执行schedule_email_send(),但我的send_an_email()中的断点永远不会到达。我在该例程中设置断点,然后单击站点上的随机页面,但sendanemail操作永远不会触发。当然,出于测试目的,我预计它会在1分钟内发射。

有谁看到我做错了什么?

php wordpress
1个回答
0
投票

这可能是由于在调用add_action函数之前触发了事件。

例如,我在'woocommerce_payment_gateways'钩子中创建了对象,并且该事件是独立于此钩子而被触发的,因此该事件没有引用类,实例或操作。我要么必须加载类,创建实例,并在每个页面加载时使用操作注册它,或者我必须将方法转换为独立于原始类的全局函数。

© www.soinside.com 2019 - 2024. All rights reserved.