Prevent SQL Injection and XSS in WordPress Plugins with Prepared Statements and Escaping

Prevent SQL injection and XSS in WordPress plugins

SQL injection and cross-site scripting (XSS) are the two most common vulnerability types in WordPress plugins. SQL injection happens when input becomes part of an SQL query; XSS when input (or stored data) is printed into HTML unescaped. WordPress has the tools for both: $wpdb->prepare() for queries, and escaping functions for every output context.

Problem: A plugin shortcode takes a category ID from the URL, puts it straight into an SQL query, and prints the results without escaping: an SQL injection point and an XSS hole for any visitor.

Solution: Validate the input (cast the ID to an integer), pass every value through prepare() placeholders, allowlist anything that cannot be a placeholder, and escape every value at the point of output with the function for its context.

The vulnerable version

<?php
// NEVER do this
function bad_category_posts() {
    global $wpdb;
    $cat = $_GET['cat']; // anything the visitor sends

    // SQL injection: ?cat=1 UNION SELECT user_login, user_pass FROM wp_users
    $rows = $wpdb->get_results(
        "SELECT p.ID, p.post_title FROM {$wpdb->posts} p
         JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.ID
         WHERE tr.term_taxonomy_id = $cat"
    );

    $out = '';
    foreach ( $rows as $row ) {
        $out .= '<li>' . $row->post_title . '</li>'; // XSS if a title contains <script>
    }
    return '<ul>' . $out . '</ul>';
}

The safe version

<?php
add_shortcode( 'category_posts', 'good_category_posts' );

function good_category_posts() {
    global $wpdb;

    // 1. Validate: a positive integer, or nothing to show
    $term_id = absint( $_GET['cat'] ?? 0 );
    if ( ! $term_id ) {
        return '';
    }

    // 2. The value goes through a placeholder
    $rows = $wpdb->get_results( $wpdb->prepare(
        "SELECT p.ID, p.post_title FROM {$wpdb->posts} p
         JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.ID
         JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
         WHERE tt.term_id = %d AND tt.taxonomy = 'category'
           AND p.post_status = 'publish' AND p.post_type = 'post'
         ORDER BY p.post_date DESC
         LIMIT %d",
        $term_id,
        10
    ) );

    // 3. Escape at output, for the context
    $out = '';
    foreach ( $rows as $row ) {
        $out .= sprintf(
            '<li><a href="%s">%s</a></li>',
            esc_url( get_permalink( $row->ID ) ), // a URL in href
            esc_html( $row->post_title )          // text
        );
    }
    return '<ul>' . $out . '</ul>';
}

For this particular task a WP_Query with 'cat' => $term_id would be even simpler and safe by design; raw SQL is shown because that is where injections happen.

What prepare() does not protect

Placeholders are only for values. Table and column names, ORDER BY fields and the sort direction cannot be placeholders, so if they come from input, choose them from an allowlist:

<?php
$orderby = in_array( $_GET['orderby'] ?? '', array( 'post_date', 'post_title' ), true ) ? $_GET['orderby'] : 'post_date';
$order   = 'ASC' === strtoupper( $_GET['order'] ?? '' ) ? 'ASC' : 'DESC';

$sql = "SELECT ID, post_title FROM {$wpdb->posts} ORDER BY $orderby $order LIMIT %d";
$rows = $wpdb->get_results( $wpdb->prepare( $sql, 20 ) );

Output escaping

Escape as late as possible, at the echo, even if the value was sanitized on input:

  • esc_html(): text between tags;
  • esc_attr(): an attribute value;
  • esc_url(): href, src;
  • wp_json_encode(): data for a <script>;
  • wp_kses_post(): rich text where some HTML is allowed.

Forms: CSRF and capabilities

<?php
add_action( 'admin_post_myplugin_save_settings', function () {
    check_admin_referer( 'myplugin_save_settings', 'myplugin_nonce' );

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'You do not have permission to do this.', 'myplugin' ), 403 );
    }

    update_option( 'myplugin_my_option', sanitize_text_field( wp_unslash( $_POST['my_option'] ?? '' ) ) );

    wp_safe_redirect( admin_url( 'options-general.php?page=myplugin&saved=1' ) );
    exit;
} );

A WordPress nonce is not single-use: it is valid for 12–24 hours for that user and action. It protects against forged requests (CSRF), but it says nothing about rights, so the capability check is always needed too.

NOTE: More on choosing the right function for each kind of input is in sanitizing and validating user input, and on the $wpdb methods in custom SQL queries with $wpdb.