On non-production sites, send every WordPress email to a test inbox, with the real recipient shown in the subject.
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;
} );
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.
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.
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.wp_mail(), aren’t covered.On staging, reset a test user’s password. The email should arrive in your test inbox with the original address in the subject.