Home / Admin / Basic WP escaping functions
Duplicate Snippet

Embed Snippet on Your Site

Basic WP escaping functions

Code Preview
php
<?php
// ❌ Don't use _e(), __(), _x() etc. to output data
<h2><?php _e('Title') ?></h2>
	
// ✅ Use the escaped versions instead esc_html_e(), esc_html__(), esc_html_x() etc.
<h2><?php esc_html_e('Title') ?></h2>
	
// ❌ Don't echo any HTML attributes without escaping
<img src="./assets/img.png" alt="<?php echo $altText ?>">
	
// ✅ Use esc_attr() to escape attributes
<img src="./assets/img.png" alt="<?php echo esc_attr($altText) ?>">
// ✅ If the attribute is a translatable string, use esc_attr_e() or esc_attr__()
<img src="./assets/img.png" alt="<?php esc_attr_e('Image contains...', 'duplicator-pro') ?>">
// ✅ If the attribute to escape is an integer use casting, esc_attr() accepts only strings
<option value="<?php echo (int) $hour ?>"><?php echo (int) $hour ?></option>
	
// ❌ Don't echo URLs without escaping
<?php echo '<a href="'. $url . '">' . esc_html( $text ) . '</a>'; ?>
// ✅ Escape URLs using esc_url()
<?php echo '<a href="'. esc_url($url) . '">' . esc_html( $text ) . '</a>'; ?>
	
// ❌ Don't use unescaped dynamic varibales for inline JavaScript
<a href="#" onclick="do_something(<?php echo $var; ?>); return false;">
	
// ✅ Escape data which will be used by JavaScript either with esc_js()
<a href="#" onclick="do_something(<?php echo esc_js($var); ?>); return false;">
// ✅ To escape data which will be used by JavaScript you can also use wp_json_encode() or json_encode()
<script type="text/javascript">
	var json = <?php echo wp_json_encode($json); ?>
	jQuery.ajax({
		...
		data: {
			action: 'action',
			states: states,
// ✅ Escape wp_create_nonce() with esc_js(), make sure to output the nonce within quotes
			nonce: '<?php echo esc_js(wp_create_nonce('DUP_PRO')); ?>'
		},
		...
	});
</script>

Comments

Add a Comment