Wordpress - 读入存储在文件中的 HTML 电子邮件模板

Wordpress - Read In HTML Email Template Stored In a File

根据我在 Wordpress 中的自定义主题,我想发送一封 HTML 电子邮件。

而不是像这样填充正文:

$message = "";
$message = "<h3>Someone has applied for a job on the site.</h3>" . "<br><br>";
$message .= "Profile Picture URL: " . $Picture . "<br>";
$message .= "Name: " . $Name . "<br>";
$message .= "Email: " . $Email . "<br>";
$message .= "Phone: " . $Phone . "<br>";
$message .= "Work Phone: " . $WorkPhone . "<br>";
$message .= "Resume: " . $Resume . "<br>";
$message .= "Preferences: " . sanitize_text_field($Preferences) . "<br><br>";

相反, 我希望 HTML 电子邮件模板是它自己的文件。

然后,我想读入 HTML 电子邮件模板文件并使用存储在 php 变量中的一些数据填充其中的部分内容。

所以,假设我有一个 html 文件:

emailtemplate.html

<h3>Name: [NameGoesHere]</h3>
<h3>Address: [AddressGoesHere]</h3>

然后,在我的 php 文件中我有:

$name = "Jane Doe";
$address = "123 Street";
$message = "";
wp_mail($to, $subject, $message, $headers, $attachments);

我如何读取那个 html 文件,将名称和地址放在它所在的位置,然后将它存储在 $message 中?

我的示例似乎太简单了,但实际上我已经构建了 3 个非常详尽的 HTML 电子邮件,每个电子邮件都有很多代码。

谢谢,

您可以使用 str_replace 来做到这一点。

首先,您需要将模板内容作为变量获取

$template = file_get_contents('/path/to/your/template.html');

然后您需要将现有变量换成放置标记。从您的示例源代码中,您可以这样交换名称字段:

$template = str_replace('[NameGoesHere]', $name, $template);

根据需要重复任何需要替换的内容。

然后当您完成后,只需将结果用作您的电子邮件内容即可。

我认为最好的自己编写的解决方案就是使用 php 内置方法对其进行解析。

要读取文件,请使用 file_get_contents:

示例:

// From Link
<?php
// <= PHP 5
$file = file_get_contents('./HTML_TEMPLATE1.html', true);
// > PHP 5
$file = file_get_contents('./HTML_TEMPLATE1.html', FILE_USE_INCLUDE_PATH);
?>

要解析 html 文件,请使用 the explode function:

我建议你放一个分隔符,例如##(稍后看看这对你有什么帮助) 它将保留实际字符串的位置。

<?php
// Example
// Use previous $file-> ($file  = "<html>...";)

$pieces = explode("#", $file);// "#" is YOUR_DELIMITER
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
?>

然后,填充数组的 odd/even 个索引(取决于您如何解析它)。

如果你按照我的建议用#解析它,你会得到一堆空的项目,你会想要用php代码中的值填充它们——只需迭代数组并设置它们。您可以从要插入的所有值创建一个数组,这样会更容易

然后将数组重新附加到字符串,然后使用 implode:

将其设置为 $message

来自 link 的简单示例:

<?php

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone
?>

然后,将其设置回 $message 并邮寄:

$message = $value_of_attached_array;
wp_mail($to, $subject, $message, $headers, $attachments);

希望这对您有所帮助:)