自从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 );