WordPress安全标准希望我逃避我的html,但如何正确地做到这一点?



我正在尝试构建一个自定义元素小部件(https://developers.elementor.com/creating-a-new-widget/)。在render()函数中,我可以把要渲染的HTML放在前端。

现在我有一个项目设置使用codesniffer强制wordpress编码标准。

我有以下渲染()函数的代码:

/**
* Render widget output on the frontend
*/
protected function render() {
$i_am                 = __( 'I am', 'hello-elementor-child' );
$and_i_am_looking_for = __( 'and I am looking for', 'hello-elementor-child' );
$output = <<<HTML
<form>
<div>
<label>$i_am</label>
<input type="text" name="i_am" value="" />
</div>
<div>
<label>$and_i_am_looking_for</label>
<input type="text" name="and_i_am_looking_for" value="" />
</div>
</form>
HTML;
echo $output;
}

CodeSniffer现在抱怨$输出,因为我没有转义它:

所有输出应该通过转义函数运行(参见WordPress开发者手册中的安全部分),找到'$output'。

PHPCS (WordPress.Security.EscapeOutput.OutputNotEscaped)

现在查看WP开发手册,它告诉我关于转义输出的几种方法,esc_html示例确实应该这样做,但是当然,然后我有前端显示html代码给用户,而不是渲染浏览器呈现的实际html…

那么在这种情况下,我如何取悦代码识别器,同时又输出我需要的内容?

您可以使用wp_kses

echo wp_kses(
$output,
array(
'form'  => array(),
'div'   => array(),
'label' => array(),
'input' => array(
'type',
'name',
'value',
),
)
);

如果你想回显php中的HTML代码。最好改成String.请像这样稍微修改一下你的代码:

$output = "<HTML>
<form>
<div>
<label>$i_am</label>
<input type='text' name='i_am' value='' />
</div>
<div>
<label>$and_i_am_looking_for</label>
<input type='text' name='and_i_am_looking_for' value='' />
</div>
</form>
</HTML>";

最新更新