How to define a HTML template for all WordPress emails?

Let’s just say it honestly, wordpress’s default emails are not as so beautifull and that’s normal because they are in text format. If you’re running a professionnal website, you probably want to brand and format every outgoing emails generated by your wordpress installation. In order to achieve that, you need to define a HTML template for all WordPress emails.

 

First we create our standard HTML mail template. You can find many free ready to use responsive templates online. Then all the variable areas of our template will be replaced by placeholders so that every time a mail is sent, the placeholders will be replaced by their proper values.

 

Let’s say for example that our template will contain 2 placeholders:
[title]: which will be replaced by the mail subject
[content]: which will be replaced by the mail message.

 

All these snippets can be added in your theme’s our child theme’s functions.php file.

 

We put our mail template in a function

function get_mail_template()
{
ob_start();
?>

[title]
 

 

Copyright © 2015 Orion.

Orion
[title]

 

[content]

 

$output= ob_get_contents(); ob_end_clean(); return $output; }

We trigger the placeholders replacements right before the mail is sent using the wp_mail wordpress filter

add_filter("wp_mail", "get_custom_mail");
function get_custom_mail($atts){
$headers[] = 'From: ORION <no-reply@orionorigin.com>';
$headers[] = 'Content-type: text/html';
$atts["headers"]=$headers;
/** we retrieve in our variable $template the template we created earlier with two placeholders **/
$template= get_mail_template();
/** we replace our placeholder [title] with the message subject **/
$output1= str_replace("[title]", $atts["subject"], $template);
/** we replace our placeholder [content] with the message content **/
$output2= str_replace("[content]", $atts["message"], $output1);
$atts["message"]=$output2;
return $atts;
}

 

And that’s it!

Changing wordpress default mail template is so easy.  But, if you have any question(s), remark(s) or just want to say hi, we would love to hear from you :D.