Use Pods for Email templates in WordPress

In some of our plugins we need to create customizable Email Templates for our customers – to e.g. let them adjust text to their Company's needs.

This is easily done – again – with the versatile Pods Framework. You could use this easy snippet to allow for templating of texts such as :

Hello {first_name},

thanks for signing up.

Cheers,
Markus

Usually we'd have to specify e.g. {@pods.first_name}, but we have a small helper function to take care of that part, to keep it simple.

/*
   This filter function allows us to keep user variables simple in the template. E.g. instead of {@pods.first_name} we can simply use {first_name}
This will only work for the Pod that is initiated in the global $pods variable. In our example this is the user pod.
*/
function add_pods_to_template($template){
    /*
    remove the following condition check if you're planning on mixing also other pods variables in your templates
    we'll use it in this example to not parse templates with a {@pods present
    */
    if(strpos($template, '{@pods') === false){
        // no {@pods found in $template, adding it
        $template = str_replace('{', '{@pods', $template);
    }
    return $template;
}

The upper str_replace() code could be also replaced with a preg_replace \{([a-z\.])\} translating to {@pods.$1} as per sc0ttkclark's suggestion. In that case the condition would fall away completely.

The main function to parse the email template with :

function parse_email_template($template, $user_id) {

    global $pods; // important
    $pods = pods('user', $user_id);

    $template = add_pods_to_template($template);

    $text = pods_evaluate_tags($template);
    return $text;

}

And here's how we'd use the function in full action :

// pull the following both variables from your WordPress database with e.g. get_option to get them from your settings page

$signup_title = "Thanks for signing up";

$signup_template = "Hello {first_name},

thanks for signing up to our product.";

// generate the text with replaced values
$signup_text = parse_email_template($signup_template, $user_id);

if(wp_mail(
    'user@email.com',
    $signup_title ,
    $signup_text 
)){
    // message was sent ...
}else{
    // message was not sent, something went wrong ...
}

That's about it – and a lot of time saved without reinventing the wheel.

Thanks to Scott Kingsley Clark for pushing forward the pods_evaluate_tags idea on irc for this behaviour. If you're not using Pods, definitely check out Scott's other solution in this gist.