首页 > 解决方案 > Wordpress如何在转义html标签时使用换行符

问题描述

我想通过使每个出现在单独的行中来分隔Welcome to %s和。Thanks for creating account on %1$s

在翻译网站上的短语时,它们目前被挤在一起/搞砸了RTL

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

标签: phphtmlwordpressline-breaksemail-confirmation

解决方案


您需要一个“换行符”将它们分开!您可以使用html以下标签:

  • br标签
  • p标签
  • h1标签

仅举几个!

但是您正在使用esc_html__translate AND escape html。为什么需要使用esc_html__从数据库中检索博客名称?为什么?

话虽如此,您可以同时使用一种白名单translate技术escape unwanted html

使用wp_kses您将能够为允许html的标签定义“白名单”并转义其余标签。

你可以阅读更多关于它的信息:

wp_kses文档

这篇关于将 html 标签列入白名单的帖子


所以你的代码会是这样的:

使用<br>标签:

protected function send_account_email( $user_data, $user_id ) {

  $whitelist_tags = array(

    'br' => array(),
  
  );
        
  $to      = $user_data['user_email'];

  $subject = sprintf(wp_kses(__('Welcome to %s <br>', 'my-plugin'), $whitelist_tags), get_option( 'blogname' ));

  $body    = sprintf( esc_html__( 'Thanks for creating account on %1$s. Your username is: %2$s ',
      'my-plugin' ), get_option( 'blogname' ), $user_data['user_login'] );
}

或使用<p>标签:

protected function send_account_email( $user_data, $user_id ) {

  $whitelist_tags = array(

    'p' => array()
  
  );
        
  $to      = $user_data['user_email'];
  
  $subject = sprintf(wp_kses(__('<p>Welcome to %s </p>', 'my-plugin'), $whitelist_tags), get_option( 'blogname' ));

  $body    = sprintf( esc_html__( 'Thanks for creating account on %1$s. Your username is: %2$s ',
      'my-plugin' ), get_option( 'blogname' ), $user_data['user_login'] );
}

或使用<h1>标签:

protected function send_account_email( $user_data, $user_id ) {

  $whitelist_tags = array(

    'h1' => array(),
  
  );
        
  $to      = $user_data['user_email'];

  $subject = sprintf(wp_kses(__('<h1>Welcome to %s </h1>', 'my-plugin'), $whitelist_tags), get_option( 'blogname' ));

  $body    = sprintf( esc_html__( 'Thanks for creating account on %1$s. Your username is: %2$s ',
      'my-plugin' ), get_option( 'blogname' ), $user_data['user_login'] );
}

笔记:

  • $whitelist_tags是一个数组,所以你可以给它添加多个标签!
  • 此外,我只在您的变量中使用了这些标签,如果需要$subject,您也可以在变量中使用确切的技术!$body
  • 我还使用__()了组合wp_kses而不是esc_html__为了translateAND escape unwanted html

推荐阅读