Send Emails in the Background
Queues emails sent by WordPress and plugins and sends them a few seconds later through WP-Cron, so form submissions, orders and registrations no longer wait for the mail server.
Opens WPIDE on
Code
add_filter( 'pre_wp_mail', function ( $return, $atts ) {
if ( null !== $return || ! empty( $GLOBALS['wpide_mail_sending'] ) || ! empty( $atts['attachments'] ) || wp_doing_cron() || ( defined( 'WP_CLI' ) && WP_CLI ) ) {
return $return;
}
$queue = (array) get_option( 'wpide_mail_queue', array() );
$queue[] = array(
'to' => $atts['to'],
'subject' => $atts['subject'],
'message' => $atts['message'],
'headers' => $atts['headers'],
);
update_option( 'wpide_mail_queue', $queue, false );
if ( ! wp_next_scheduled( 'wpide_send_mail_queue' ) ) {
wp_schedule_single_event( time() + 5, 'wpide_send_mail_queue' );
}
return true;
}, 99, 2 );
add_action( 'wpide_send_mail_queue', function () {
$queue = (array) get_option( 'wpide_mail_queue', array() );
delete_option( 'wpide_mail_queue' );
$GLOBALS['wpide_mail_sending'] = true;
foreach ( $queue as $mail ) {
if ( ! empty( $mail['to'] ) ) {
wp_mail( $mail['to'], $mail['subject'], $mail['message'], $mail['headers'] );
}
}
unset( $GLOBALS['wpide_mail_sending'] );
} );
Notes
Emails with attachments are sent immediately, because temporary attachment files may be gone later; make sure WP-Cron runs reliably.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.