You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress转义HTML标签时如何添加换行符适配RTL站点

解决方案

你需要根据发送的邮件格式(HTML/纯文本)选择对应换行方案,核心原则是不要把换行符/HTML标签放到需要转义的翻译字符串内,避免esc_html__将其转义为普通文本导致换行失效,同时保证所有动态内容的转义生效。


情况1:发送HTML格式邮件

HTML中换行需要使用<br>标签,拆分两段翻译内容后单独拼接换行标签即可,同时建议增加dir属性适配RTL排版,避免不同方向文字混排错乱:

protected function send_account_email( $user_data, $user_id ) {
            
  $to      = $user_data['user_email'];
  $subject = sprintf( esc_html__( 'Welcome to %s', 'my-plugin' ), esc_html( get_option( 'blogname' ) ) );
  // 拆分两段独立的翻译字符串
  $welcome_line = sprintf( esc_html__( 'Welcome to %s', 'my-plugin' ), esc_html( get_option( 'blogname' ) ) );
  $account_line = sprintf( esc_html__( 'Thanks for creating account on %1$s. Your username is: %2$s', 'my-plugin' ), 
    esc_html( get_option( 'blogname' ) ), 
    esc_html( $user_data['user_login'] ) 
  );
  // 拼接换行标签,外层加dir="auto"自动适配RTL/LTR内容方向
  $body = '<div dir="auto">' . $welcome_line . '<br>' . $account_line . '</div>';
}

情况2:发送纯文本格式邮件

纯文本格式使用跨系统兼容的PHP_EOL常量作为换行符即可:

protected function send_account_email( $user_data, $user_id ) {
            
  $to      = $user_data['user_email'];
  $subject = sprintf( esc_html__( 'Welcome to %s', 'my-plugin' ), esc_html( get_option( 'blogname' ) ) );
  $welcome_line = sprintf( esc_html__( 'Welcome to %s', 'my-plugin' ), esc_html( get_option( 'blogname' ) ) );
  $account_line = sprintf( esc_html__( 'Thanks for creating account on %1$s. Your username is: %2$s', 'my-plugin' ), 
    esc_html( get_option( 'blogname' ) ), 
    esc_html( $user_data['user_login'] ) 
  );
  $body = $welcome_line . PHP_EOL . $account_line;
}

额外说明

  • 上述写法中所有动态输出的站点名、用户名都单独做了esc_html转义,比原有写法安全性更高,不会引入XSS风险
  • HTML邮件外层的dir="auto"会自动根据内容判断文字方向,RTL站点下可以有效避免阿拉伯语、希伯来语等RTL文字和LTR格式的用户名、站点名混排时的排版错位问题
  • 翻译字符串完全独立,不会影响多语言翻译的适配,翻译人员可以正常翻译两段内容,不需要处理任何代码标签

内容的提问来源于stack exchange,提问作者JustinB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 04:27:03