Sanitization and escaping
Last modified on Sun 11 Oct 2020
We follow WordPress VIP's guidelines
- Never trust user input.
- Escape as late as possible.
- Escape everything from untrusted sources (like databases and users), third-parties (like Twitter), etc.
- Never assume anything.
- Never trust user input.
- Sanitation is okay, but validation/rejection is better.
- Never trust user input.
Every output has to be escaped. Even translatable strings. This means that instead of using __()
and _e()
, we have to use esc_html__()
, esc_html_e()
, esc_attr__()
, esc_attr_e()
, wp_kses()
, wp_kses_post()
, and other escaping functions.
When writing data to the database, be sure to sanitize the variables
sanitize_text_field( wp_unslash( $_POST['my_data'] ) )
and to prepare your database queries.
<?php
$meta = 'Custom meta';
$postId = $_GET['post_id'];
$wpdb->query(
$wpdb->prepare(
"DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s",
$postId, $meta
)
);
This is especially important when dealing with user input from front end (forms).