Sanitization

Sanitization in WordPress refers to the process of cleaning and filtering input data before saving it to the database. Since user-submitted data (from forms, requests, or APIs) can be manipulated by attackers, sanitization ensures that only valid, safe, and expected values are stored. WordPress provides a wide set of sanitization functions that help developers prevent malicious input, avoid database corruption, and reduce the risk of cross-site scripting (XSS) and SQL injection attacks.

How it works

  • Sanitization functions transform input into a safe format before storage.
  • Common functions include:
    • sanitize_text_field() → strips tags and encodes special characters.
    • sanitize_email() → validates and formats email addresses.
    • sanitize_url() → ensures the string is a properly formatted URL.
    • intval() or absint() → ensures numeric values are integers.
  • Data is typically sanitized when processing $_POST, $_GET, or $_REQUEST values in custom forms or settings pages.

Why it matters

Without sanitization, attackers could inject malicious JavaScript, SQL commands, or invalid data into the database. This could lead to defacement, data theft, or full site compromise. Sanitization is a cornerstone of secure WordPress development and is required when handling any data coming from users or third-party sources.

Examples

Processing and sanitizing form input:

if (isset($_POST['user_name'])) {
    $username = sanitize_text_field($_POST['user_name']);
    update_user_meta(get_current_user_id(), 'custom_username', $username);
}

Sanitizing custom options before saving:

function myplugin_sanitize_option($input) {
    return sanitize_email($input);
}
register_setting('myplugin_options', 'admin_email', 'myplugin_sanitize_option');