Stop non-production sites sending any email at all, while logging what would have been sent.
add_filter( 'pre_wp_mail', function ( $return, array $atts ) {
if ( 'production' === wp_get_environment_type() ) {
return $return;
}
error_log( sprintf(
'[email blocked on %s] To: %s | Subject: %s',
wp_get_environment_type(),
is_array( $atts['to'] ) ? implode( ', ', $atts['to'] ) : $atts['to'],
$atts['subject']
) );
return true; // Pretend it was sent so nothing reports an error.
}, 10, 2 );
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.
If you don’t need to see emails on a staging or development site, the safest option is to send none at all. This snippet blocks them and writes a line to the error log instead.
Since WordPress 5.7, pre_wp_mail runs before any email is built. Returning anything other than null skips sending. The snippet returns true, so plugins think the email went out and don’t show errors.
WP_ENVIRONMENT_TYPE to staging, development or local in wp-config.php. On production nothing changes.wp_mail() is blocked.On staging, reset a password. No email should arrive, and the error log should show an “[email blocked on staging]” line.