How to automatically send a email with a Cron and Action Scheduler in WordPress

Viewed 17

I wrote a pseudo code to send an email to users after publishing a custom post which works partially. And I would like to use wp_mail asynchronously to avoid server expiration errors. Thanks for any help.

add_action('transition_post_status', 'send_mails_on_publish', 10, 3);

function send_mails_on_publish($new_status, $old_status, $post)
{

    if (
        'publish' !== $new_status or 'publish' === $old_status or
        'gestion_calendrier' !== get_post_type($post)
    ) {
        return;
    } else {
        $headers = 'From: "Your Site <example@gmail.com>' . "\r\n" . 'Reply-To: example@gmail.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion();
        $headers .= "Content-Transfer-Encoding: 8bit\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\n";
        $headers .= 'MIME-Version: 1.0' . "\r\n";
        $subscribers = get_users(array('role' => 'subscriber'));
        $emails      = array();
        foreach ($subscribers as $subscriber)
            $emails[] = $subscriber->user_email;

        $body = sprintf(
            'Hey there is a new entry!
            See <%s>',
            get_permalink($post)
        );

        wp_mail($emails, 'New entry!', $body,  $headers);
    }
}
0 Answers
Related