Copy Admin Notification Emails to Slack
Posts the subject and the start of every email sent to the site admin address into a Slack channel, so the team sees new users, comments and alerts where they already work.
Opens WPIDE on
Code
add_filter( 'wp_mail', function ( $atts ) {
$url = defined( 'WPIDE_SLACK_WEBHOOK_URL' ) ? (string) WPIDE_SLACK_WEBHOOK_URL : '';
$admin = strtolower( (string) get_option( 'admin_email' ) );
$to = strtolower( implode( ',', (array) $atts['to'] ) );
if ( 0 !== strpos( $url, 'https://hooks.slack.com/' ) || false === strpos( $to, $admin ) ) {
return $atts;
}
$escape = function ( $text ) {
return str_replace( array( '&', '<', '>' ), array( '&', '<', '>' ), (string) $text );
};
$text = sprintf( "*%s*\n%s", $escape( wp_strip_all_tags( (string) $atts['subject'] ) ), $escape( wp_html_excerpt( trim( wp_strip_all_tags( (string) $atts['message'] ) ), 500, '…' ) ) );
wp_safe_remote_post( $url, array(
'body' => wp_json_encode( array( 'text' => $text ) ),
'headers' => array( 'Content-Type' => 'application/json' ),
'timeout' => 5,
'blocking' => false,
) );
return $atts;
}, 900 );
Notes
Define WPIDE_SLACK_WEBHOOK_URL in wp-config.php; only emails addressed to the admin email are copied, and they are still sent as usual.
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.