Skip to content

Instantly share code, notes, and snippets.

@dhimaskirana
Last active October 7, 2020 14:58
Show Gist options
  • Save dhimaskirana/9f0d615c47a9c04abfc200a3eaba3f5d to your computer and use it in GitHub Desktop.
Save dhimaskirana/9f0d615c47a9c04abfc200a3eaba3f5d to your computer and use it in GitHub Desktop.
Custom HTML Template to wp_mail()
<?php
/**
* Plugin Name: Custom Email Template wp_mail()
* Plugin URI: https://pakaiwp.com/
* Description: Plugin sederhana untuk menggunakan custom html pada fungsi wp_mail()
* Version: 1.0
* Requires at least: 5.2
* Requires PHP: 7.2
* Author: Dhimas Kirana
* Author URI: https://www.dhimaskirana.com/
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
/**
* Custom HTML Template to wp_mail()
*
* Replace myprefix_ with your prefix
*
* The HTML Template saved as custom-email-template.php in the same folder
*
*/
function myprefix_email_template( $message ) {
// Render Template
ob_start();
include( 'custom-email-template.php' );
$myprefix_template = ob_get_contents();
ob_end_clean();
// Replace Placeholder
$message = str_replace('%%MAILCONTENT%%', $message, $myprefix_template);
// Replace Some Placeholder
$to_replace = array(
'%%HOME_URL%%' => get_option( 'home' ),
'%%BLOG_NAME%%' => get_option( 'blogname' ),
'%%BLOG_DESCRIPTION%%' => get_option( 'blogdescription' )
);
foreach ($to_replace as $placeholder => $var ) {
if(is_array($var) ) {
do {
$var = reset($var);
} while(is_array($var));
}
$message = str_replace($placeholder, $var, $message);
}
// Return Template with Data
return $message;
}
add_filter( 'wp_mail_content_type', 'set_content_type' );
function set_content_type($type) {
if( $type != 'text/html' ) {
// If not html, work with content and filter it
add_filter( 'myprefix_filter_email', 'wp_kses_post', 50 );
myprefix_content_filters();
}
return $content_type = 'text/html';
}
add_filter( 'wp_mail', 'my_wp_mail_filter' );
function my_wp_mail_filter( $args ) {
$message = $args['message'];
$args['message'] = myprefix_email_template( apply_filters('myprefix_filter_email', $message) );
return $args;
}
function myprefix_content_filters() {
add_filter( 'myprefix_filter_email', 'wptexturize' );
add_filter( 'myprefix_filter_email', 'convert_chars' );
add_filter( 'myprefix_filter_email', 'wpautop' );
add_filter( 'myprefix_filter_email', 'clean_retrieve_password' );
}
function clean_retrieve_password( $message ) {
return make_clickable( preg_replace( '@<(http[^> ]+)>@', '$1', $message ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment