Skip to content

Instantly share code, notes, and snippets.

@marcbacon
Last active November 15, 2023 22:15
Show Gist options
  • Save marcbacon/fd9ec89f09bdb29363656d8e32982644 to your computer and use it in GitHub Desktop.
Save marcbacon/fd9ec89f09bdb29363656d8e32982644 to your computer and use it in GitHub Desktop.
Add Email Template to WordPress Theme
<?php
/**
* Use an HTML Email Template for All Sends
* Add this file to functions.php
*/
function your_email_template($args) {
if (!is_array($args)) {
return $args;
}
if (isset($args["message"]) && isset($args["subject"]) && isset($args["headers"])) {
// Test that this is not already an HTML email
// Test that this message does not already include an <html> or <body> tag. This seems to add compatibility for most plugins
if ( !str_contains($args["message"], '<html') && !str_contains($args["message"], '<HTML') && !str_contains($args["message"], '<body') ) {
// Automatically add spacing
$message = wpautop($args["message"]);
$subject = $args["subject"];
// Load your custom email template file
ob_start();
include(get_template_directory() . '/email-template.php');
$email_template = ob_get_clean();
// Replace placeholders with actual content
$email_template = str_replace('{email_subject}', $subject, $email_template);
$email_template = str_replace('{email_content}', $message, $email_template);
$args["message"] = $email_template;
// If the headers are not set then update them so that this is sent as an HTML email instead of plain text
if ( !is_array($args["headers"]) && $args["headers"] === '' ) {
$args["headers"] = 'Content-Type: text/html; charset=UTF-8';
}
}
}
return $args;
}
add_filter('wp_mail', 'your_email_template', 10, 1);
<?php
/**
* Custom HTML Email Template
* {email_subject} will be replaced with the email subject
* {email_content} will be replaced with the email content
*/
?>
<!DOCTYPE html>
<html>
<head>
<title>{email_subject}</title>
</head>
<body>
<h1>{email_subject}</h1>
{email_content}
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment