在 js 代码中转义数据

esc_js() 旨在用于标记属性中的内联 JS。

对于 <script> 标签内的数据,请使用 wp_json_encode()

<input type="text" onfocus="if( this.value == '<?php echo esc_js( $fields['input_text'] ); ?>' ) { this.value = ''; }" name="name">

wp_json_encode() 将变量编码为 JSON,并进行一些健全性检查。

请注意,wp_json_encode() 会自动包含字符串分隔引号。

<?php
$book = array(
    "title" => "JavaScript: The Definitive Guide",
    "author" => "Stack Overflow",
);
?>
<script type="text/javascript">
var book = <?php echo wp_json_encode($book) ?>;
/* var book = {
    "title": "Security in WordPress",
    "author" => "Stack Overflow",
}; */
</script>

要么

<script type="text/javascript">
    var title = <?php echo wp_json_encode( $title ); ?>;
    var content = <?php echo wp_json_encode( $content ); ?>;
    var comment_count = <?php echo wp_json_encode( $comment_count ); ?>;
</script>