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' . "rn";
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.
Per my comment to your question, I believe the problem is that
include
ing files, whether directly or usingget_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.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.
Here is the sample code for using output buffering. You will be able to access all the variables inside the template which are defined above “include line”.
The function
get_template_part()
doesn’t return the HTML but echo it (it useslocate_template()
which loads the file – echo).You can either turn output buffering on using
ob_start()
and put the buffer in to your variable or you can usefile_get_contents()
.On your case I think the best solution is this: