Email PHP Intermediate

Send All Email to One Address on Staging

On non-production sites, send every WordPress email to a test inbox, with the real recipient shown in the subject.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 16 lines
add_filter( 'wp_mail', function ( array $args ): array {
	if ( 'production' === wp_get_environment_type() ) {
		return $args;
	}

	$original = is_array( $args['to'] ) ? implode( ', ', $args['to'] ) : (string) $args['to'];

	$args['to']      = 'dev-inbox@example.com';
	$args['subject'] = '[' . strtoupper( wp_get_environment_type() ) . ' → ' . $original . '] ' . $args['subject'];

	// Drop Cc and Bcc so no copies reach real people.
	$headers         = is_array( $args['headers'] ) ? $args['headers'] : explode( "\n", str_replace( "\r\n", "\n", (string) $args['headers'] ) );
	$args['headers'] = array_values( array_filter( $headers, fn ( $h ): bool => ! preg_match( '/^\s*(cc|bcc)\s*:/i', (string) $h ) ) );

	return $args;
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

A staging copy of a live site has real customer emails in its database. One test order or password reset can email a real person. This snippet sends everything to your own test inbox instead, so you can still check emails without risk.

How it works

The wp_mail filter changes every email before it’s sent. On any environment other than production, the snippet replaces the recipient with your test address and adds the environment and original recipient to the subject, like [STAGING → jane@example.com] Your order.

Cc and Bcc headers are removed so copies don’t slip through.

Things to watch

  • Set define( 'WP_ENVIRONMENT_TYPE', 'staging' ); in the staging site’s wp-config.php. Without it, the site counts as production and emails go out normally.
  • Plugins that send through their own API, not wp_mail(), aren’t covered.

How to test it

On staging, reset a test user’s password. The email should arrive in your test inbox with the original address in the subject.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only