【问题标题】:Sending email of Post in Wordpress with special characters在 Wordpress 中发送带有特殊字符的 Post 电子邮件
【发布时间】:2014-11-16 11:58:28
【问题描述】:

我制作了一个插件,每次在 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>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Email test</title>
</head>
<body>
    <table cellpadding="0" cellspacing="0" border="0" id="backgroundTable">
        <tr>
            <td valign="top"> 
                <table cellpadding="0" cellspacing="0" border="0" align="center">
                    <tr>
                        <td width="20" valign="top"></td>
                        <td width="560" valign="top">%%CONTENT%%</td>
                        <td width="20" valign="top"></td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>  
</body>
</html>

我将 %%CONTENT%% 字符串替换为帖子中的内容。我尝试通过各种功能和过滤器运行内容,包括:apply_filters、htmlspecialchars() 和 htmlentities(),但没有成功。当我在 Outlook 中收到电子邮件时,里面有奇怪的字符。我的帖子包含一些特殊字符,例如 £、&、“、” 和度数符号 °C。

这是插件代码:

function post_published_notification( $ID, $post ) {
    global $post;
    $author = $post->post_author; /* Post author ID. */
    $name = get_the_author_meta( 'display_name', $author );
    $email = get_the_author_meta( 'user_email', $author );
    $title = $post->post_title;
    $to[] = sprintf( '%s <%s>', $name, $email );
    $subject = sprintf( 'Published: %s', $title );

    $content = $post->post_content;
    $content = apply_filters('the_content', $content);

    $html_content = file_get_contents(__DIR__.'/email_components/email.html');
    $message = str_replace('%%CONTENT%%', $content, $html_content);

    $headers[] = 'MIME-Version: 1.0' . "\r\n";
    $headers[] = 'Content-type: text/html; charset="UTF-8' . "\r\n";

    wp_mail( $to, $subject, $message, $headers );
}
add_action( 'publish_post', 'post_published_notification', 10, 2 );

所以我的问题是如何让这些字符安全地正确显示在电子邮件主题和电子邮件正文中?非常感谢!迈克

【问题讨论】:

    标签: php wordpress email post special-characters


    【解决方案1】:

    最后,在尝试了许多不同的选项后,我通过使用 wordpress 循环输出我的电子邮件内容解决了这个问题:

    $thepost = new WP_Query('post_type=news&p='.$post_id);
    if($thepost->have_posts()) {
        while($thepost->have_posts()) {
            //runs once to get the one queried post
            $thepost->the_post();
            $content = wpautop(get_the_content());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-12
      • 1970-01-01
      • 2010-12-15
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      相关资源
      最近更新 更多