{"id":28,"date":"2019-11-07T11:17:55","date_gmt":"2019-11-07T17:17:55","guid":{"rendered":"https:\/\/travisolson.net\/code\/?p=28"},"modified":"2019-11-07T11:20:13","modified_gmt":"2019-11-07T17:20:13","slug":"wordpress-email-templating-system-for-your-custom-plugin","status":"publish","type":"post","link":"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/","title":{"rendered":"WordPress: Email Templating System for Your Custom Plugin"},"content":{"rendered":"<p>If you&#8217;re creating a plugin and you want an easy way to generate HTML emails within a standard template, then this code should get you most of the way there.\u00a0 It allows for passing an array of data to the template, which is a must-have feature.\u00a0 Importantly, it also provides a way for users to override the templates in their own theme.<\/p>\n<p>The core template function:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">function myprefix_get_email_from_template($template_name, $template_data) {\r\n  $html = '';\r\n  $path = false;\r\n  \r\n  $override_path = get_template_directory() . '\/email\/'.$template_name.'.php';\r\n  $template_path = plugin_dir_path( __FILE__ ) . 'assets\/email\/'.$template_name.'.php';\r\n  if (file_exists($override_path)) {\r\n    $path = $override_path;\r\n  }\r\n  elseif (file_exists($template_path)) {\r\n    $path = $template_path;\r\n  }\r\n  \r\n  if ($path) {\r\n    ob_start();\r\n    include($path);\r\n    $html = ob_get_clean();\r\n  }\r\n  \r\n  return $html;\r\n}<\/pre>\n<p>It first looks for the template in the &#8220;email&#8221; directory of the current theme. If not found, it defaults to the &#8220;assets\/email&#8221; directory of the plugin.\u00a0 You can change the plugin path to whatever you would like.<\/p>\n<p>If the template file is found it will then start output buffering, capturing the output of the included template file into the $html variable.<\/p>\n<p>To enable HTML in the wp_mail() function we need to create a filter function. This filter can be added immediately before calling wp_mail() and then removed immediately after.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">\/\/ Function called by wp_mail_content_type filter to enable HTML enable.\r\nfunction myprefix_wp_mail_content_type_html() {\r\n  return 'text\/html';\r\n}<\/pre>\n<p>A sample implementation of the email template function, along with the code to actually send the email:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">function myprefix_send_invitation_email() {\r\n  $email_data = array(\r\n    'recip_name'   =&gt; trim(sanitize_text_field($_POST['first_name']) . ' ' . sanitize_text_field($_POST['last_name'])),\r\n    'email'        =&gt; sanitize_text_field($_POST['email']),\r\n    'sender_name'  =&gt; get_customer_name($sender_id),\r\n    'register_url' =&gt; get_site_url(null, '\/my-account\/?register=1&amp;invite_token='.urlencode($invite_token))\r\n  );\r\n  $body = myprefix_get_email_from_template('invite-a-friend', $email_data);\r\n  \r\n  $subject =  'An invitation from ' . $email_data['sender_name'];\r\n  $to = $email_data['recip_name'] . '&lt;' . $email_data['email'] . '&gt;';\r\n  add_filter( 'wp_mail_content_type', 'myprefix_wp_mail_content_type_html' );\r\n  $sent = wp_mail($to, $subject, $body);\r\n  remove_filter( 'wp_mail_content_type', 'myprefix_wp_mail_content_type_html' );\r\n}<\/pre>\n<p>Of course you will need to create templates also.\u00a0 Here is a sample &#8220;invite-a-friend&#8221; template:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&lt;?php include('head.php'); ?&gt;\r\n&lt;?php if ($template_data['recip_name'] != '') { ?&gt;\r\n&lt;p style=\"color:#ffffff; font-size:14px;\"&gt;Dear &lt;?php echo esc_html($template_data['recip_name']); ?&gt;,&lt;\/p&gt;\r\n&lt;?php } ?&gt;\r\n&lt;p style=\"color:#ffffff; font-size:14px;\"&gt;Your friend, &lt;?php echo esc_html($template_data['sender_name']); ?&gt;, thinks that you will enjoy our website, and has invited you to join. If you are interested in becoming a member, simply follow the link below.&lt;\/p&gt;\r\n\r\n&lt;p style=\"color:#ffffff; font-size:14px;\"&gt;Please &lt;a href=\"&lt;?php echo esc_attr($template_data['register_url']); ?&gt;\" style=\"color:#ffffff;\"&gt;click here&lt;\/a&gt; to register today.&lt;\/p&gt;\r\n\r\n&lt;p style=\"color:#ffffff; font-size:14px;\"&gt;Very best wishes,&lt;br \/&gt;The Example Company&lt;\/p&gt;\r\n\r\n&lt;?php include('foot.php'); ?&gt;<\/pre>\n<p>All variables are included in the $template_data array, which we passed in from the myprefix_get_email_from_template() function.\u00a0 Also note that the first and last line of the template are including head.php and foot.php, respectively. You&#8217;ll need to add those files into your plugins email templates directory.\u00a0 This is where you&#8217;ll add your re-usable email template HTML.\u00a0 At the least you&#8217;ll want to add &lt;html&gt; and &lt;body&gt; tags, and most likely you&#8217;ll add your company logo and some contact info.\u00a0 I&#8217;m not going to go into the details of generating HTML for emails since that&#8217;s a whole other subject that already has volumes written about it.<\/p>\n<p>If you want to use the template system, but be able to generate the entire email body on the fly, you can create a generic email template file such as assets\/email\/generic.php, with the following content:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&lt;?php include('head.php'); ?&gt;\r\n&lt;div style=\"color:#000000;\"&gt;\r\n&lt;?php echo $template_data['content']; ?&gt;\r\n&lt;\/div&gt;\r\n&lt;?php include('foot.php'); ?&gt;<\/pre>\n<p>Then you can use the following to return your custom HTML within the template, assuming that $body contains your HTML:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">$email_msg = myprefix_get_email_from_template('generic', array('content' =&gt; $body));<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>If you&#8217;re creating a plugin and you want an easy way to generate HTML emails within a standard template, then this code should get you most of the way there.\u00a0 It allows for passing an array of data to the template, which is a must-have feature.\u00a0 Importantly, it also provides a way for users to&#8230;  <a class=\"excerpt-read-more\" href=\"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/\" title=\"Read WordPress: Email Templating System for Your Custom Plugin\">Read more &raquo;<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-28","post","type-post","status-publish","format-standard","hentry","category-wordpress"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>WordPress: Email Templating System for Your Custom Plugin - Travis Olson&#039;s Code Snippets<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"WordPress: Email Templating System for Your Custom Plugin - Travis Olson&#039;s Code Snippets\" \/>\n<meta property=\"og:description\" content=\"If you&#8217;re creating a plugin and you want an easy way to generate HTML emails within a standard template, then this code should get you most of the way there.\u00a0 It allows for passing an array of data to the template, which is a must-have feature.\u00a0 Importantly, it also provides a way for users to... Read more &raquo;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/\" \/>\n<meta property=\"og:site_name\" content=\"Travis Olson&#039;s Code Snippets\" \/>\n<meta property=\"article:published_time\" content=\"2019-11-07T17:17:55+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2019-11-07T17:20:13+00:00\" \/>\n<meta name=\"author\" content=\"Travis Olson\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Travis Olson\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/\"},\"author\":{\"name\":\"Travis Olson\",\"@id\":\"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/0170ab5b2e7a3d88436375cc50336934\"},\"headline\":\"WordPress: Email Templating System for Your Custom Plugin\",\"datePublished\":\"2019-11-07T17:17:55+00:00\",\"dateModified\":\"2019-11-07T17:20:13+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/\"},\"wordCount\":378,\"publisher\":{\"@id\":\"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/0170ab5b2e7a3d88436375cc50336934\"},\"articleSection\":[\"WordPress\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/\",\"url\":\"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/\",\"name\":\"WordPress: Email Templating System for Your Custom Plugin - Travis Olson&#039;s Code Snippets\",\"isPartOf\":{\"@id\":\"https:\/\/www.travisolson.net\/code\/#website\"},\"datePublished\":\"2019-11-07T17:17:55+00:00\",\"dateModified\":\"2019-11-07T17:20:13+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.travisolson.net\/code\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"WordPress: Email Templating System for Your Custom Plugin\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.travisolson.net\/code\/#website\",\"url\":\"https:\/\/www.travisolson.net\/code\/\",\"name\":\"Travis Olson&#039;s Code Snippets\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/0170ab5b2e7a3d88436375cc50336934\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.travisolson.net\/code\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/0170ab5b2e7a3d88436375cc50336934\",\"name\":\"Travis Olson\",\"logo\":{\"@id\":\"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/image\/\"},\"url\":\"https:\/\/www.travisolson.net\/code\/author\/travis-olson\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"WordPress: Email Templating System for Your Custom Plugin - Travis Olson&#039;s Code Snippets","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/","og_locale":"en_US","og_type":"article","og_title":"WordPress: Email Templating System for Your Custom Plugin - Travis Olson&#039;s Code Snippets","og_description":"If you&#8217;re creating a plugin and you want an easy way to generate HTML emails within a standard template, then this code should get you most of the way there.\u00a0 It allows for passing an array of data to the template, which is a must-have feature.\u00a0 Importantly, it also provides a way for users to... Read more &raquo;","og_url":"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/","og_site_name":"Travis Olson&#039;s Code Snippets","article_published_time":"2019-11-07T17:17:55+00:00","article_modified_time":"2019-11-07T17:20:13+00:00","author":"Travis Olson","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Travis Olson","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/#article","isPartOf":{"@id":"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/"},"author":{"name":"Travis Olson","@id":"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/0170ab5b2e7a3d88436375cc50336934"},"headline":"WordPress: Email Templating System for Your Custom Plugin","datePublished":"2019-11-07T17:17:55+00:00","dateModified":"2019-11-07T17:20:13+00:00","mainEntityOfPage":{"@id":"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/"},"wordCount":378,"publisher":{"@id":"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/0170ab5b2e7a3d88436375cc50336934"},"articleSection":["WordPress"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/","url":"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/","name":"WordPress: Email Templating System for Your Custom Plugin - Travis Olson&#039;s Code Snippets","isPartOf":{"@id":"https:\/\/www.travisolson.net\/code\/#website"},"datePublished":"2019-11-07T17:17:55+00:00","dateModified":"2019-11-07T17:20:13+00:00","breadcrumb":{"@id":"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.travisolson.net\/code\/wordpress-email-templating-system-for-your-custom-plugin\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.travisolson.net\/code\/"},{"@type":"ListItem","position":2,"name":"WordPress: Email Templating System for Your Custom Plugin"}]},{"@type":"WebSite","@id":"https:\/\/www.travisolson.net\/code\/#website","url":"https:\/\/www.travisolson.net\/code\/","name":"Travis Olson&#039;s Code Snippets","description":"","publisher":{"@id":"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/0170ab5b2e7a3d88436375cc50336934"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.travisolson.net\/code\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/0170ab5b2e7a3d88436375cc50336934","name":"Travis Olson","logo":{"@id":"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/image\/"},"url":"https:\/\/www.travisolson.net\/code\/author\/travis-olson\/"}]}},"_links":{"self":[{"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/posts\/28","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/comments?post=28"}],"version-history":[{"count":3,"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/posts\/28\/revisions"}],"predecessor-version":[{"id":31,"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/posts\/28\/revisions\/31"}],"wp:attachment":[{"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/media?parent=28"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/categories?post=28"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/tags?post=28"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}