When Data Must be Sanitized, Escaped, and Validated in WordPress

Categories:

In WordPress, you must sanitize, validate, and escape data at different points to ensure security and data integrity. Here’s a simple rule to follow:

1. SANITIZE – When Accepting Input (Before Saving to Database)

Sanitization ensures that data is clean before storing it in the database.

🔹 When to sanitize?

  • When processing $_POST, $_GET, $_REQUEST, $_FILES, etc.
  • When storing data using update_option(), update_post_meta(), insert_post(), etc.

🔹 How to sanitize?
Use appropriate sanitization functions based on the expected data type:

Data TypeFunction to UseExample
Text inputsanitize_text_field()$title = sanitize_text_field( $_POST['title'] );
Emailsanitize_email()$email = sanitize_email( $_POST['email'] );
URLesc_url_raw()$url = esc_url_raw( $_POST['url'] );
Integerabsint()$age = absint( $_POST['age'] );
Floatfloatval()$price = floatval( $_POST['price'] );
HTMLwp_kses_post() (allowed HTML)$content = wp_kses_post( $_POST['content'] );
Checkbox (Boolean)boolval()$checked = boolval( $_POST['checkbox'] );
JSONjson_decode() + array_map()$data = json_decode( stripslashes( $_POST['json_data'] ), true ); array_walk_recursive( $data, 'sanitize_text_field' );

Example: Correct Way to Sanitize Data Before Saving

if ( isset( $_POST['icwcu_custom_services_title'] ) ) {
    $custom_services_title = sanitize_text_field( wp_unslash( $_POST['icwcu_custom_services_title'] ) );
    update_post_meta( $post_id, 'icwcu_custom_services_title', $custom_services_title );
}

2. VALIDATE – Before Using the Data

Validation ensures that the sanitized data is in the expected format.

🔹 When to validate?

  • When checking if data meets specific criteria (e.g., is an email valid? Is a number in a certain range?)
  • Before processing critical information (e.g., order amounts, email addresses, etc.).

🔹 How to validate?
Use proper WordPress functions or custom validation logic:

Data TypeValidation FunctionExample
Emailis_email()if ( ! is_email( $email ) ) { return new WP_Error( 'invalid_email', 'Invalid email address' ); }
Integeris_numeric()if ( ! is_numeric( $price ) ) { return new WP_Error( 'invalid_number', 'Price must be a number' ); }
URLfilter_var( $url, FILTER_VALIDATE_URL )if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) { return new WP_Error( 'invalid_url', 'Invalid URL' ); }
Booleanin_array( $value, [ 'yes', 'no' ] )if ( ! in_array( $value, [ 'yes', 'no' ] ) ) { return new WP_Error( 'invalid_choice', 'Invalid value' ); }

Example: Validating Data Before Using

$email = sanitize_email( $_POST['email'] );
if ( ! is_email( $email ) ) {
    wp_die( 'Invalid email address provided.' );
}

3. ESCAPE – When Outputting Data

Escaping ensures that data is safe when displayed on the screen, preventing XSS (Cross-Site Scripting) attacks.

🔹 When to escape?

  • When displaying data in HTML, JavaScript, URLs, or attributes.
  • When using echo, printf(), return, etc.

🔹 How to escape?
Use esc_*() functions based on where the data is being output:

ContextFunction to UseExample
HTML Textesc_html()echo esc_html( $name );
HTML Attributesesc_attr()<input type="text" value="<?php echo esc_attr( $name ); ?>">
URLsesc_url()<a href="<?php echo esc_url( $url ); ?>">Link</a>
JavaScriptesc_js()<script>var name = "<?php echo esc_js( $name ); ?>";</script>
SQL Queriesesc_sql()$wpdb->prepare( "SELECT * FROM table WHERE column = %s", esc_sql( $value ) );

Example: Escaping Data Before Displaying

echo '<h2>' . esc_html( get_option( 'icwcu_custom_services_title' ) ) . '</h2>';
echo '<a href="' . esc_url( get_option( 'icwcu_custom_services_link' ) ) . '">Click Here</a>';

Final Cheat Sheet

ActionWhen to UseExample Function
SanitizeBefore saving to databasesanitize_text_field(), sanitize_email(), esc_url_raw(), absint()
ValidateBefore processing user inputis_email(), is_numeric(), filter_var( $url, FILTER_VALIDATE_URL )
EscapeBefore outputting to screenesc_html(), esc_attr(), esc_url(), esc_js()

Conclusion

  • Sanitize input before storing it 🛑 (e.g., from $_POST, $_GET, $_REQUEST).
  • Validate input before processing it ✅ (e.g., checking formats).
  • Escape output before displaying it 🏁 (e.g., when using echo, print, HTML).

This will help you to make a secure WordPress plugin or theme! 🚀

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *