Как сделать электронные письма WordPress асинхронными
Недавно у меня возникла проблема на моем сайте, когда электронные письма не отправлялись. Это было проблемой, но еще большая проблема заключалась в том, что сбой привел к тайм-ауту сценария, что действительно ухудшило работу пользователя.
Я публикую свое решение для создания wp_mail
асинхронного в надежде получить некоторые отзывы об этой идее. Это хорошее решение? С какими подводными камнями я столкнусь?
1
1 answers
Поскольку wp_mail
подключаем, мы можем выборочно переопределить его. Я запускаю следующий код в своем плагине общей функциональности:
/**
* Email Async.
*
* We override the wp_mail function for all non-cron requests with a function that simply
* captures the arguments and schedules a cron event to send the email.
*/
if ( ! defined( 'DOING_CRON' ) || ( defined( 'DOING_CRON' ) && ! DOING_CRON ) ) {
function wp_mail() {
// Get the args passed to the wp_mail function
$args = func_get_args();
// Add a random value to work around that fact that identical events scheduled within 10 minutes of each other
// will not work. See: http://codex.wordpress.org/Function_Reference/wp_schedule_single_event
$args[] = mt_rand();
// Schedule the email to be sent
wp_schedule_single_event( time() + 5, 'cron_send_mail', $args );
}
}
Затем у меня есть следующая функция, определенная для фактической отправки электронного письма.
/**
* This function runs during cron requests to send emails previously scheduled by our
* overrided wp_mail function. We remove the last argument because it is just a random
* value added to make sure the cron job schedules correctly.
*
* @hook cron_send_mail 10
*/
function example_cron_send_mail() {
$args = func_get_args();
// Remove the random number that was added to the arguments
array_pop( $args );
call_user_func_array( 'wp_mail', $args );
}
/**
* Hook the mail sender. We accept more arguments than wp_mail currently takes just in case
* they add more in the future.
*/
add_action( 'cron_send_mail', 'example_cron_send_mail', 10, 10 );
5
Author: Dominic P, 2015-04-24 19:28:02