Home / Admin / Escaping data with wp_kses
Duplicate Snippet

Embed Snippet on Your Site

Escaping data with wp_kses

Code Preview
php
<?php
	
// ❌ Don't use html tags in escaping functions like esc_html, esc_attr and their localized equivalents
// Expected output: This part of the text is <b>bold</b> and this part <u>underlined</u>.
esc_html_e(
	'This part of the text is <b>bold</b> and this part <u>underlined</u>.',
	'duplicator-pro'
);
	
// ✅ Use wp_kses to allow specified html tags
echo wp_kses(
	__(
		'This part of the text is <b>bold</b> and this part <u>underlined</u>.',
		'duplicator-pro'
	),
	[
		'b' => [],
		'u' => [],
	]
);
// ✅ Use ViewHelper::GEN_KSES_TAGS constant to escape <b>, <i>, <u> html tags
echo wp_kses(
	__(
		'This part of the text is <b>bold</b> and this part <u>underlined</u>.',
		'duplicator-pro'
	),
	ViewHelper::GEN_KSES_TAGS
);
// ❌ When attributes are not provided to each allowed html element, they will be stripped away
// Expected output: <a>Some text</a>
echo wp_kses(
	$this->getHtmlLocationLink(),
	[
		'a' => [],
	]
);
// ✅ The attributes of an html element need to provided explicitly
// Expected output: <a href="https://example.com" target="_blank" rel="noopener">Some text</a>
echo wp_kses(
	$this->getHtmlLocationLink(),
	[
		'a' => [
			'href'   => [],
			'target' => [],
		],
	]
);

Comments

Add a Comment