Code Snippet: Redirect All Emails on Staging Site

When troubleshooting a production site, one of the challenge is dealing with the email communication. For example, we need to debug a problem on eCommerce website, but don’t want the actual client get interrupted by all the testing emails. Here is the code I use in troubleshooting. It redirects all outgoing emails to me without disturbing any registered user.

To debug, first thing to do is to create a staging site, never troubleshoot or make change directly on live site. After setup staging site, put following code in functions.php or custom plugin of your own.

add_filter( 'wp_mail', 'tbwp_staging_email_filter', 10, 1 );

function tbwp_staging_email_filter( $args ) {

	// Get original To address
	$original_to = $args['to'];

	// Send to developer only
	$args['to'] = 'deverloper@mycompany.com';

	// Show original To address in message for debug
	$args['message'] = sprintf( "Message is originally sent to: [%s]", $original_to ) . $args['message'];

	return $args;
}

Remember to replace “developer@mycompany.com” to your own email address and disable this code on production site (in case you copy staging to live site)