I’m using wp_mail()
to send an HTML email. But there’s quite a lot of HTML code in the email, so rather than including all the code in my wp_mail()
function, is it possible to have the code in a separate template and just include this template in the function? Here is what I have:
<?php if ( isset( $_POST['submitted'] )) {
add_filter('wp_mail_content_type',create_function('', 'return "text/html"; '));
$emailTo = 'person@gmail.com' ;
$subject="This is the subject";
$body = get_template_part( 'includes/my_email_template' );
$headers="From: My Name" . "\r\n";
wp_mail($emailTo, $subject, $body, $headers);
}?>
I’d like to be able to put all of my HTML code in ‘my_email_template’ but when I try this, no email is sent. Am I including the template incorrectly? Thanks in advance for any answers.
3 Answers
Per my comment to your question, I believe the problem is that include
ing files, whether directly or using get_template_part
isn’t likely to give you a string to pass to $body
and that is going to cause errors in the code, or at the very least unespected behavior.
I would avoid reading files into memory and just create a function that returns your $body
content.
function get_email_body_wpse_96357() {
$body = '<p>Hi</p>';
return $body;
}
Then use $body = get_email_body_wpse_96357();
as needed. An advantage of this method is that you can easily pass parameters to the function if you ever decide to do so. You could also use variables in an included file but it can be messy.
If you don’t want to load that function all the time, then put it in a file by itself and include that file only when you need the function.