WordPress Sanitizing And Escaping Cheat Sheet: Secure Your Code
Two rules keep WordPress code safe: sanitize input when data comes in, and escape output when data goes out to the browser. Sanitize early, escape late.
Sanitize input
Clean data before saving it or using it.
sanitize_text_field(): a single line of text.sanitize_textarea_field(): multi line text.sanitize_email(): an email address.sanitize_title(): a slug.sanitize_file_name(): a file name.sanitize_hex_color(): a color like#ff4500.esc_url_raw(): a URL that will be saved or used in a redirect.absint(): a positive integer.wp_kses_post(): HTML, keeping only the tags allowed in post content.
$lotgrafix_name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
$lotgrafix_email = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
$lotgrafix_id = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : 0;
Escape output
Escape every value at the moment you print it.
esc_html(): text inside an HTML tag.esc_attr(): a value inside an HTML attribute.esc_url(): a URL inhreforsrc.esc_js(): a string inside inline JavaScript.esc_textarea(): content inside a textarea.wp_kses_post(): HTML that should keep safe tags like links and bold.
<a href="<?php echo esc_url( $lotgrafix_link ); ?>" title="<?php echo esc_attr( $lotgrafix_title ); ?>">
<?php echo esc_html( $lotgrafix_text ); ?>
</a>
Escape and translate in one step
esc_html__(): returns an escaped translated string.esc_html_e(): prints an escaped translated string.esc_attr__()andesc_attr_e(): the same for attributes.
<h2><?php esc_html_e( 'Latest News', 'lotgrafix' ); ?></h2>
Allow only specific HTML tags
$lotgrafix_allowed = array(
'a' => array( 'href' => array(), 'title' => array() ),
'strong' => array(),
'em' => array(),
);
echo wp_kses( $lotgrafix_html, $lotgrafix_allowed );
Quick rules
- Never trust
$_POST,$_GET,$_REQUESTor$_COOKIE. - Use
wp_unslash()before sanitizing superglobals, because WordPress adds slashes to them. - Escape even data from your own database. It may have been saved by someone else or by another plugin.
- Use the escaping function that matches the context where the value is printed.
November 3, 2026


