Wrap Emails in a Template File From Your Theme
Wraps every plain-text WordPress email in an HTML template file stored in your theme, so designers can edit the email layout like any other template.
Opens WPIDE on
Code
add_filter( 'wp_mail', function ( $atts ) {
$template = locate_template( 'emails/wrapper.php' );
$headers = is_array( $atts['headers'] ) ? implode( "\n", $atts['headers'] ) : (string) $atts['headers'];
if ( ! $template || false !== stripos( $headers, 'text/html' ) || preg_match( '/<(html|body|p|div|table)\b/i', (string) $atts['message'] ) ) {
return $atts;
}
$subject = wp_strip_all_tags( (string) $atts['subject'] );
$content = make_clickable( nl2br( esc_html( (string) $atts['message'] ) ) );
ob_start();
include $template;
$html = trim( (string) ob_get_clean() );
if ( '' === $html ) {
return $atts;
}
$atts['message'] = $html;
$type = 'Content-Type: text/html; charset=' . get_bloginfo( 'charset' );
if ( is_array( $atts['headers'] ) ) {
$atts['headers'][] = $type;
} else {
$atts['headers'] = trim( $headers . "\n" . $type );
}
return $atts;
}, 20 );
Notes
Create emails/wrapper.php in your (child) theme using $content (safe HTML) and $subject; without the file emails are unchanged, and do not combine it with another HTML wrapper snippet.
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.