Validation, Sanitization and Escaping

Use the correct security operation at each stage of the data lifecycle.

2 min read

  • Article
  • Intermediate
  • 2 minutes read
  • Reviewed August 4, 2026

Secure WordPress code treats data according to where it comes from and where it is going.

Validation, sanitization and escaping are related but distinct operations.

Validation

Validation tests whether data matches the expected rules.

Examples include:

  • An integer greater than zero.
  • A value from a known list.
  • A valid email address.
  • A recognized date format.
  • An object ID the current user can access.

Reject invalid values instead of trying to repair them when the accepted format is clear.

Sanitization

Sanitization cleans or normalizes data before storage or processing.

Choose a function that matches the expected type. A text field, key, email, URL and allowed HTML fragment require different handling.

Sanitization should not silently turn arbitrary input into a different privileged instruction.

Escaping

Escaping prepares data for a specific output context.

Escape as late as possible and choose the correct context:

  • HTML text.
  • HTML attribute.
  • URL.
  • JavaScript.
  • textarea.
  • allowed HTML.

Data stored safely can still become dangerous if output into the wrong context without escaping.

Do Not Trust the Database

Values in the database can originate from old code, imports, compromised accounts or external APIs.

Escape output even when the value was originally sanitized.

Prepared SQL

Use $wpdb->prepare() for dynamic SQL values.

Validation and escaping for HTML do not make a concatenated SQL query safe.

Common Mistakes

Avoid:

  • Sanitizing instead of authorizing.
  • Escaping before storage.
  • Using one generic sanitizer for every field.
  • Trusting administrator input automatically.
  • Double escaping.
  • Using strip_tags() as a complete security strategy.
  • Outputting JSON or JavaScript through HTML-only functions.

Frequently Asked Questions

Is validation better than sanitization?

When a strict valid format exists, validation and rejection are generally more precise.

Should data be escaped before saving?

Usually escape for the final output context, not for database storage.

Continue Learning

Previous: [Nonces in WordPress](/resources/wordpress-manual/security/nonces/)

Next: [Securing WordPress File Uploads](/resources/wordpress-manual/security/securing-file-uploads/)