Использование шаблонов WordPress для HTML-писем


Я работаю над плагином, который должен отправлять электронное письмо после отправки формы.

Я использую wp_mail() для этого, и это прекрасно работает. Моя проблема в том, что в моем коде HTML генерируется с помощью набора строк PHP, добавляемых в переменную, например:

$content = $html_headers;
$content .= '<h1>' . the_title($post_id) . '</h1>';
$content .= '<p>' . $post_body . '</p>;

..etc

В настоящее время у меня более 30 таких строк; и это позволяет мне, наконец, сделать:

    //add filter to allow html
    add_filter('wp_mail_content_type', create_function('', 'return "text/html"; '));

    //Send email
    wp_mail( '[email protected]', 'mail tester', $content, 'From: some one <[email protected]>' );

    //remove filter to allow html (avoids some conflict.)
    remove_filter('wp_mail_content_type', create_function('', 'return "text/html"; '));

Я бы предпочел, чтобы я мог ссылаться на отдельный файл, в котором используется обычная тема WordPress шаблоны-теги для того, чтобы генерировать содержимое почты, чтобы в отдельном файле у меня было что-то вроде этого:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        (headertags)
    </head>
    <body>
        <h1><?php the_title($post_id); ?></h1>
        <p><?php my_custom_template_body_tag(); ?></p>
    </body>
</html>

Но я не знаю, как затем вернуть это содержимое в функцию wp_mail(). Я пробовал использовать file_get_contents(), но это просто игнорирует контент, сгенерированный PHP, и я изучил синтаксис heredoc. Но я нахожу это довольно уродливым и подверженным ошибкам. Есть ли у меня другие варианты? Мне действительно понравилось бы, если бы я мог сделать что-то вроде этого:

$content = parse_and_return_content_of('path/to/template/file', $arg);

Спасибо

Author: butlerblog, 2014-09-30

2 answers

Вы должны использовать ob_get_contents()

    ob_start();
    include('template/email-header.php');
    printf(__('<p>A very special welcome to you, %1$s. Thank you for joining %2$s!</p>', 'cell-email'), $greetings, get_bloginfo('name'));
    printf(__('<p> Your password is <strong style="color:orange">%s</strong> <br> Please keep it secret and keep it safe! </p>', 'cell-email'), $plaintext_pass);
    printf(__('<p>We hope you enjoy your stay at %s. If you have any problems, questions, opinions, praise, comments, suggestions, please feel free to contact us at any time</p>', 'cell-email'), get_bloginfo('name'));
    include('template/email-footer.php');
    $message = ob_get_contents();
    ob_end_clean();
    wp_mail($user_email, $email_subject, $message);

И на template/email-header.php, вы можете использовать

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta property="og:title" content="<?php echo $email_subject ?>" />
    <title><?php echo $email_subject ?></title>
</head>
<body leftmargin="0" marginwidth="0" topmargin="0" marginheight="0" offset="0" style="width: 100% !important; -webkit-text-size-adjust: none; margin-top: 0; margin-right: 0; margin-bottom: 0; margin-left: 0; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; background-color: #FAFAFA;" bgcolor="#FAFAFA">
<!-- the rest of the html here -->
<?php // and php generated content if you prefer ?>
 4
Author: ifdion, 2015-01-18 00:42:44

Вы могли бы сделать что-то более похожее на объединение полей. Таким образом, вы можете разделить свой html и PHP, используя шаблон электронной почты с заполнителями и выполнив замену строки на них. Что-то вроде следующего:

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        (headertags)
    </head>
    <body>
        <h1>[POST.TITLE]</h1>
        <p>[POST.CONTENT]</p>
    </body>
</html>

PHP

$html_email_template_file = 'some/path/mytemplate-example.html';

// assign contents of file to $content var
$content = file_get_contents($html_email_template_file);

$content = str_replace('[POST.TITLE]', $post->post_title, $content);
$content = str_replace('[POST.CONTENT]', $post->post_excerpt, $content);

// send your email here ...
 2
Author: Aron, 2019-04-14 12:15:48