SQL injection occurs when user-supplied data enters an SQL query as part of its structure. The source may be form fields, URL parameters, cookies, AJAX requests, or values passed through the REST API. If the code does not separate data from SQL commands, an attacker may gain access to records, change settings, create an account, or use the vulnerability to launch a further attack.
In WordPress, the primary protection in custom PHP code is prepared queries through the $wpdb object, proper input validation, and restricted access rights. Sanitization alone does not make an SQL query safe, while plugins and AJAX handlers require separate review.
How SQL Injection Occurs in WordPress
An unsafe scenario begins with concatenating a variable and an SQL string. For example, a value from a URL or form parameter is added directly to a WHERE condition. Even if the field is intended for ordinary search, an attacker can submit a specially crafted string that changes the query logic.
The risk is particularly high in functions that work with custom tables, filters, search, sorting, data imports, and statistics. Standard WordPress functions often hide the details of database operations, but custom SQL code in plugins and themes remains the developer's responsibility.
- The data source may be more than a form: check URLs, cookies, headers, AJAX requests, and REST parameters.
- Authentication does not eliminate the risk: a compromised or ordinary account may have access to a vulnerable handler.
- SQL injection can lead not only to reading data but also to changing settings if the query has write access.
Use $wpdb->prepare() for Values
In WordPress, variable values should be passed through $wpdb->prepare(), using placeholders of the appropriate type: %s for strings, %d for integers, and %f for floating-point numbers. Data should be supplied as separate arguments rather than inserted directly into the SQL string.
A prepared query separates the SQL structure from its values. This substantially reduces the risk that special characters in user input will be interpreted as part of an SQL command.
- Use %d for IDs and additionally verify that the value has the expected type.
- Use %s for text, even if the field normally contains only a few characters.
- Do not add quotation marks around a placeholder: the query-preparation mechanism handles them.
- Check the operation's result and handle errors without showing the SQL query text to the user.
$user_id = absint( $_GET['user_id'] ?? 0 );
$sql = $wpdb->prepare(
"SELECT ID, user_login FROM {$wpdb->users} WHERE ID = %d",
$user_id
);
$user = $wpdb->get_row( $sql );
$email = sanitize_email( $_POST['email'] ?? '' );
$sql = $wpdb->prepare(
"SELECT ID FROM {$wpdb->users} WHERE user_email = %s",
$email
);
$user_id = $wpdb->get_var( $sql );
Why Escaping Is Not a Replacement for prepare()
Sanitization functions are intended to bring data into an expected format—for example, by cleaning an email address, URL, or text field. They do not determine where an SQL value ends and its syntax begins. Therefore, even after using sanitize_text_field(), a variable should not be concatenated with a query.
The correct approach is to combine validation or sanitization with prepare(). The former checks whether a value complies with business rules, while the latter passes it safely to SQL.
Data Validation and Safe Sorting
Placeholders are intended for values, not column names, SQL operators, or sort directions. You cannot pass a column name through %s and expect it to become part of the query structure.
For such parameters, use an allowlist—a predefined list of permitted options. The user-supplied value should only select one of the safe options; it must not enter SQL without control.
- Use absint() or another integer validation method for IDs.
- For lists of statuses, types, and action modes, compare values against an allowlist.
- For ASC and DESC, do not accept arbitrary text—convert it to one of two fixed options.
- For column names, maintain a mapping between the external key and a specific SQL identifier.
$allowed_order = [
'date' => 'post_date',
'title' => 'post_title',
];
$order_key = sanitize_key( $_GET['order'] ?? 'date' );
$order_by = $allowed_order[ $order_key ] ?? $allowed_order['date'];
$direction = strtoupper( $_GET['direction'] ?? 'DESC' );
$direction = in_array( $direction, [ 'ASC', 'DESC' ], true )
? $direction
: 'DESC';
$sql = "SELECT ID, post_title FROM {$wpdb->posts}
WHERE post_status = %s
ORDER BY {$order_by} {$direction}";
$sql = $wpdb->prepare( $sql, 'publish' );
Secure Forms, AJAX, and Elementor
Forms and AJAX handlers often become weak points because they accept data directly from the browser. A field hidden in HTML or created in Elementor is not proof of authorization: the user can modify it before submitting the request.
Every handler must verify the nonce for CSRF protection, the current user's capabilities, and the validity of the data itself. A nonce does not replace authorization and does not protect against SQL injection—it only helps confirm that the request was generated in an allowed context.
- Verify the nonce on the server rather than merely generating one in the form.
- Use current_user_can() before reading or changing data when the action is restricted to certain roles.
- Do not trust user_id, post_id, price, status, or role values received from the browser: verify them on the server.
- After validation, pass values to SQL through $wpdb->prepare().
- For public forms, limit request frequency and do not return unnecessary data in the AJAX response.
check_ajax_referer( 'my_action', 'nonce' );
if ( ! current_user_can( 'edit_posts' ) ) {
wp_send_json_error( [ 'message' => 'Недостатньо прав.' ], 403 );
}
$post_id = absint( $_POST['post_id'] ?? 0 );
$sql = $wpdb->prepare(
"SELECT ID FROM {$wpdb->posts} WHERE ID = %d AND post_type = %s",
$post_id,
'post'
);
$found_id = $wpdb->get_var( $sql );
What to Check in Elementor Integrations
In Elementor forms and add-ons, pay attention to custom PHP handlers, webhook logic, AJAX actions, and functions that write submissions to custom tables. The builder itself does not make arbitrary third-party code secure.
During an audit, determine which fields arrive from the form, where they are stored, who can call the handler, and whether query parameters are prepared before being sent to the database. Pay particular attention to functions available without authentication.
How to Audit a Plugin or Theme
Begin the audit by locating every use of $wpdb, as well as the get_results(), get_row(), get_var(), query(), insert(), update(), and delete() methods. Review not only visible pages but also administrative actions, cron tasks, REST routes, and AJAX.
For every query, document the source of each parameter and how it is validated. If a variable is built from several parts, check each part separately: for example, a filter value may be safe while the sort direction is not.
- Find concatenation of SQL strings with $_GET, $_POST, $_REQUEST, $_COOKIE, or REST parameters.
- Check whether all numeric values are actually passed as numbers rather than merely cleaned as text.
- Review queries in functions available to unauthenticated users.
- Check the plugin's custom tables: table and column names must be fixed or pass through an allowlist.
- Test negative scenarios on a copy of the site without using destructive queries on the production database.
Additional Protection at the WordPress and Server Levels
Secure code should be the foundation, but protection must be supplemented with appropriate access rights and site monitoring. The WordPress database account should not have more privileges than the specific site requires. This does not eliminate the vulnerability, but it may limit the consequences of a compromise.
Update WordPress, plugins, and themes regularly, remove unused components, and restrict access to the administration area. Backups should be stored separately from the server and periodically tested by performing a restoration.
Web server, PHP, and security-system logs help identify unusual requests, database errors, or a spike in requests to a single handler. A WAF can filter some common attacks, but it does not replace fixing vulnerable code.
- Use a separate database or database user for different sites where possible.
- Do not show visitors SQL errors, stack traces, or diagnostic messages.
- Apply the principle of least privilege to WordPress users and database accounts.
- After an incident, check not only the plugin file but also users, settings, cron tasks, and database contents.
Common Developer Mistakes
The most common mistake is assuming that sanitize_text_field() or esc_sql() automatically makes arbitrary SQL safe. Such functions should not be used to justify concatenation. Another mistake is protecting only the form while leaving the same handler accessible through a direct AJAX request.
Problems also occur when a developer uses %d for a value that should actually be a string or allows the user to provide a column name. After making changes, test not only the positive scenario but also empty, overly long, invalid, and specially crafted values.
- Do not use $_REQUEST without a clear understanding of the parameter's source.
- Do not rely on hidden fields, cookies, or nonces as proof of authorization.
- Do not output a database error directly in the response to the user.
- Do not assume that a third-party plugin is secure merely because it is popular or has been installed for a long time.
- Do not fix one query while ignoring other paths to the same table.
Frequently asked questions
Is sanitize_text_field() alone enough to protect against SQL injection?
No. Sanitization helps bring input into an expected format, but it does not replace a prepared SQL query. Use $wpdb->prepare() for values and an allowlist for column names and sorting.
Does $wpdb->prepare() protect table and column names?
Placeholders are intended for values, not arbitrary SQL identifiers. Table names, column names, and sort directions must be defined in code or selected from a strictly limited list.
Is a nonce required for protection against SQL injection?
A nonce primarily protects against CSRF and does not replace prepare() or capability checks. A secure AJAX handler needs all these layers: a nonce, authorization, validation, and a prepared query.
Where should I look for SQL injection vulnerabilities in WordPress?
Review custom theme and plugin code, search, filters, imports, forms, AJAX handlers, REST routes, and work with custom tables. Pay particular attention to actions available anonymously.
What should I do if I suspect SQL injection on a site?
Restrict access to the vulnerable function, preserve logs, create a verified backup, and audit files, users, and the database. Do not test destructive queries on a production site; involve an incident-response specialist if necessary.
Conclusion
Protecting WordPress from SQL injection starts with a simple rule: never place variables inside an SQL string without preparing the query. Use $wpdb->prepare() for values, validate types, restrict identifiers through an allowlist, and check capabilities in every AJAX or REST handler.
During an audit, do not limit yourself to forms visible to users. Review the entire data path—from Elementor, a URL, or a cookie to the database query—as well as updates, logs, backups, and server access rights.