如何正确转义过滤后的内容变量?

How to properly escape a filtered content variable?

我正在 运行 通过我的 Wordpress 主题的主题检查器插件,我有以下代码片段:

1.仅获取并显示 post 内容中的第一个嵌入视频:

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

$embeds = get_media_embedded_in_content( $content );
$first_embedded = $embeds[0];
echo $first_embedded;
  ?>

2。从 post 内容中删除任何嵌入的内容:

   <?php 
     $content = apply_filters( 'the_content', $post->post_content );
     $content = preg_replace("/(<iframe[^<]+<\/iframe>)/", '', $content);
     echo $content;
     ?>

我在主题检查器中收到此警告:

WARNING: Found echo $ in the file single.php. Possible data validation issues found. All dynamic data must be correctly escaped for the context where it is rendered.
Line 34: echo $first_embedded;
Line 76: echo $content;

我怎样才能正确地转义这些变量? 我试过:

<?php esc_html( $first_embedded); ?>

但它只打印我的嵌入式视频的 HTML <iframe>...</iframe> 代码,就好像它是一个简单的文本字符串一样。

如果我在$content上做同样的事情:

 <?php esc_html( $content); ?>

我是初学者。问题是我需要这两个变量,因为第一个变量显示视频,以防 post 格式是视频类型,并用第一个嵌入视频替换 post 缩略图。

为了不在 post 的内容中显示该视频,还需要第二个功能。

我找到了一个很好的解决方法,可以在 Theme Checker 上顺利进行,当然,在 WordPress 页面上也可以,即使用 html_entity_decode()

所以我替换了:

echo $first_embedded;

这一行:

echo html_entity_decode( esc_html( $first_embedded ) );

并且:

echo $content;

与:

echo html_entity_decode( esc_html($content) );

html_entity_decode() 函数将 HTML 实体转换为字符,这就是我们需要显示过滤后 post 内容的代码并且在 Envato 或 WP 主题中没有错误检查器.