Leave a Reply

3 comments

  1. Per my comment to your question, I believe the problem is that includeing 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.

  2. 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”.

    WordPress: Include template in the email.

    ob_start();
    include(get_stylesheet_directory() . '/assets/email-templates/booking-details-template.php');
    $email_content = ob_get_contents();
    ob_end_clean();
    $headers = array('Content-Type: text/html; charset=UTF-8');
    wp_mail($to_email, "Booking details", $email_content, $headers);
    
  3. The function get_template_part() doesn’t return the HTML but echo it (it uses locate_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 use file_get_contents().

    On your case I think the best solution is this:

    $body = file_get_contents(TEMPLATEPATH . 'includes/my_email_template.php');