Skip to content

Instantly share code, notes, and snippets.

@xnau
Last active September 5, 2020 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xnau/6940f00cef03c95d86b77f0acbd49e4e to your computer and use it in GitHub Desktop.
Save xnau/6940f00cef03c95d86b77f0acbd49e4e to your computer and use it in GitHub Desktop.
Shows how to wrap an outgoing WordPress email with structural HTML such as a doctype, meta tags, style, etc.
<?php
/*
* Plugin Name: xnau HTML Email Wrapper
* Description: Adds a structural HTML wrapper to outgoing WordPress emails.
*/
class xnau_email_html_wrapper {
/**
*
*/
public function __construct()
{
add_filter( 'wp_mail', array($this, 'wrap_wp_email_body') );
}
/**
* wraps the email body of all WP outgoing emails
*
* @param array $args the email components
* @return array the modified components
*/
public function wrap_wp_email_body( $args )
{
$args['message'] = str_replace( '{body}', $args['message'], $this->wrapper() );
return $args;
}
/**
* provides the html wrapper
*
* this wrapper must contain the {body} placeholder where the unwrapped email body goes
*
* this wrapper is based on an article in emailonacid.com
*
* @see https://www.emailonacid.com/blog/article/email-development/which-code-should-i-include-in-every-email/
* @return string
*/
private function wrapper()
{
ob_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin:0;padding:0;min-width:100%;background-color:#ffffff;">
<table width="100%" border="0" cellpadding="0" cellspacing="0" style="min-width: 100%;" role="presentation">
<tr>
<td>
{body}
</td>
</tr>
</table>
</body>
</html>
<?php
return ob_get_clean();
}
}
// invoke the class
new xnau_email_html_wrapper;
@xnau
Copy link
Author

xnau commented Aug 11, 2020

This will wrap the body of all outgoing emails that use the WordPress core to send.

To apply this selectively, you'd inspect the values in the $args array to determine whether to apply the wrap, or possibly apply a different wrap.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment