【问题标题】:Delaying a loop in WordPress延迟 WordPress 中的循环
【发布时间】:2017-03-10 00:11:49
【问题描述】:

我编写了以下函数,该函数将在发布帖子时向每个用户发送电子邮件。它工作得很好,但我遇到的问题是发布帖子可能需要一些时间,因为它需要通过 while 循环运行的次数。目前有 110 名成员。

现在我的问题是,有没有一种简单的方法可以延迟这个过程,以便帖子可以发布,然后电子邮件发送功能作为一项任务在后台处理?

function send_email_notifications() {
    $args = array(
        'post_type' => 'members',
        'orderby' => 'title',
        'order' => 'ASC',
        'posts_per_page' => -1,
        'post_parent' => 0,
        'post_status' => array('pending', 'draft', 'publish'),
    );

    $emailSearch = new WP_Query($args);

    if(isset($_REQUEST['send_email_notification'])) {
        if($emailSearch->have_posts()) {
            while($emailSearch->have_posts()) {
                $emailSearch->the_post();

                wp_mail('test@test.com', 'Test', 'Test');
            }
        }
    }
}
add_action('publish_notifications', 'send_email_notifications', 10, 2);

【问题讨论】:

  • 当然。您正在寻找“作业调度程序”。

标签: php wordpress email


【解决方案1】:

您可能会发现 WordPress Cron 很有用。在您的 publish_notifications() 函数中,您可以拥有:

$args['subject'] = //something
$args['message'] = //something else
$args['to']      = //an email address

wp_schedule_single_event( time() + 3600, 'email_about_post', $args);

然后在其他地方你可以有类似的东西:

function email_about_post_function($args) {
    wp_mail($args['to'], $args['subject'], $args['message']);
}
add_action( 'email_about_post','email_about_post_function' );

警告 - 我没有测试这个特定的代码。阅读更多https://codex.wordpress.org/Function_Reference/wp_schedule_event

【讨论】:

  • 感谢詹姆斯的指导。进一步研究了 wp_schedule_single_event 函数,我认为这正是我想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多