2016-10-27 176 views
2

我写了下面的函数,当发布帖子时将通过电子邮件发送给每个用户。它工作得很好,但我遇到的问题是,由于需要通过while循环运行的次数,发布帖子可能需要一些时间。目前有110名成员。在WordPress中延迟循环

现在对于我的问题,是否有一个简单的方法来延迟这个过程,以便后可以发布然后电子邮件发送功能是在后台照顾作为一项任务?

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('[email protected]', 'Test', 'Test'); 
      } 
     } 
    } 
} 
add_action('publish_notifications', 'send_email_notifications', 10, 2); 
+1

当然。 “工作调度程序”就是你正在寻找的。 – arkascha

回答

2

您可能会发现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

+0

感谢您的指导,詹姆斯。进一步观察了wp_schedule_single_event函数,我认为这正是我正在寻找的。 –