Blog / Build with AI /
Making a WordPress plugin secure: nonces, sanitising and escaping
AI will happily write you a WordPress plugin that works. It adds a settings page, saves a value, shows it on the site. You test it, it does what you asked, and you feel great.
Then someone points out that any logged-in user can change your settings, that a crafty link could trick an admin into changing them, and that the saved value can inject a script into every page. The plugin works. It isn’t safe.
Security in WordPress plugins comes down to a few habits with long names: nonces, capability checks, sanitising and escaping. Once you see the pattern, you’ll spot the gaps in any plugin, including ones an AI wrote for you.
The mental model: trust nothing coming in, escape everything going out
Think of your plugin as a restaurant kitchen.
- Who’s allowed in? (capability checks: is this person permitted to do this?)
- Did they really mean to order this? (nonces: is this request genuine?)
- Is the ingredient safe to use? (sanitising: clean data before storing it)
- Is the plate safe to serve? (escaping: make output harmless when printing it)
Miss any one, and trouble gets through.
1. Capability checks: who is allowed?
A page or action should only work for users with the right permission. In WordPress, you check with current_user_can():
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( 'You do not have permission to do this.' );
}
manage_options is the permission for site settings, normally held by administrators. Pick the lowest capability that fits the job. Hiding a menu item isn’t security; the check must run when the action runs, not just when the menu is drawn.
2. Nonces: was this request really intended?
A nonce (“number used once”, though in WordPress it’s valid for a limited time and works as a token) protects against cross-site request forgery. That’s a trick where a malicious page makes your logged-in browser send a request to your site without you knowing, such as clicking a link that changes a setting.
A nonce proves the request came from a form or link your own site generated for this user.
Add one to a form:
<form method="post">
<?php wp_nonce_field( 'myplugin_save_settings', 'myplugin_nonce' ); ?>
<input type="text" name="myplugin_title" value="<?php echo esc_attr( $title ); ?>">
<?php submit_button(); ?>
</form>
Check it when handling the form:
if ( ! isset( $_POST['myplugin_nonce'] )
|| ! wp_verify_nonce( $_POST['myplugin_nonce'], 'myplugin_save_settings' ) ) {
wp_die( 'Security check failed.' );
}
The action name (‘myplugin_save_settings’) must match in both places. For admin pages, check_admin_referer( 'myplugin_save_settings', 'myplugin_nonce' ) does the verification and dies on failure in one line.
Nonces also apply to links that do something (delete, activate) and to AJAX requests. For AJAX, create the nonce on the PHP side, pass it to your script, and verify with check_ajax_referer().
A nonce isn’t a login or a permission check. It answers “did the user mean this?”, not “may the user do this?”. You need both.
3. Sanitising: clean data on the way in
Anything from $_POST, $_GET, $_REQUEST, a REST request or an uploaded file is untrusted input. Clean it for its expected type before you use or store it:
| Data | Function |
|---|---|
| Plain text | sanitize_text_field() |
| Multi-line text | sanitize_textarea_field() |
sanitize_email() |
|
| URL to store | esc_url_raw() |
| Whole number | absint() or intval() |
| Checkbox | isset( $_POST['x'] ) ? 1 : 0 |
| HTML you allow, such as a limited editor | wp_kses_post() |
| File name | sanitize_file_name() |
For input read from the superglobals, also unslash first, because WordPress adds slashes:
$title = isset( $_POST['myplugin_title'] )
? sanitize_text_field( wp_unslash( $_POST['myplugin_title'] ) )
: '';
update_option( 'myplugin_title', $title );
Sanitising is also about validating: if a value must be one of three options, check it’s one of three, rather than just cleaning it.
$allowed = array( 'left', 'right', 'center' );
$align = in_array( $_POST['align'] ?? '', $allowed, true ) ? $_POST['align'] : 'left';
4. Escaping: make output harmless
Sanitising protects your data. Escaping protects your pages. Whenever you print something to the screen, escape it for the place it’s going:
| Where it goes | Function |
|---|---|
| Between tags | esc_html() |
| Inside an attribute | esc_attr() |
| Into a link or src | esc_url() |
| Inside a textarea | esc_textarea() |
| Allowed HTML | wp_kses_post() |
echo '<h2>' . esc_html( get_option( 'myplugin_title' ) ) . '</h2>';
If the stored title were <script>alert(1)</script>, esc_html() would turn it into harmless visible text. Without it, the script would run for every visitor: that’s cross-site scripting, and it’s among the most common plugin flaws.
A rule worth memorising: sanitise on the way in, escape on the way out, and escape even if you believe the data is clean. Data can come from places you forgot, or change later. Escape late, at the moment of output.
Translation functions have escaping versions too: esc_html__() and esc_html_e().
5. Database queries
If you write your own SQL, never put variables straight into the query. Use $wpdb->prepare():
global $wpdb;
$row = $wpdb->get_row(
$wpdb->prepare( "SELECT * FROM {$wpdb->prefix}myplugin WHERE id = %d", $id )
);
%d is for a number, %s for a string. Prepared statements prevent SQL injection. Better still, use WordPress’s built-in functions (get_option, WP_Query, and so on) when they fit.
6. Three smaller habits
- Block direct file access. At the top of PHP files:
if ( ! defined( 'ABSPATH' ) ) { exit; }. - REST routes need a permission callback. Never leave it open by accident; return a proper capability check.
- Prefix everything (functions, options, handles) to avoid collisions with other plugins.
Asking AI for secure code
Don’t assume AI writes secure PHP. Ask for it:
Write this settings page for a WordPress plugin. Include a capability check, a nonce on the form with verification on save, sanitisation for every input and escaping for every output. Add a comment above each security measure saying what it protects against.
Then review with this prompt:
Audit this plugin code for security problems: missing capability checks, missing nonce verification, unsanitised input, unescaped output, and unprepared SQL. List each issue with the line and a fix.
AI audits help but aren’t complete. Follow up with the checklist below, by eye, on every form and every echo. For the wider picture, securing AI-built tools: API keys, permissions and other traps covers the habits beyond WordPress, and building a WordPress plugin with AI: the workflow that works shows where this check fits in a build.
The checklist
- Does every action check
current_user_can()? - Does every form, link and AJAX call use a nonce, and is it verified?
- Is every input sanitised or validated?
- Is every output escaped for its context?
- Does every SQL query with variables use
prepare()? - Are secrets stored safely, and not printed or logged?
- Does uninstalling clean up options and data?
Key takeaways
- Capability checks decide who may; nonces decide whether they meant to.
- Sanitise input; escape output; do both.
- Use the right function for each context.
- Prepare any SQL with variables.
- Review AI-written plugin code against a checklist.
FAQ
Do I need a nonce on a front-end form?
Yes, for any action that changes data for a logged-in user. For public forms, other protections such as rate limits or spam checks matter too.
Is sanitize_text_field enough?
For plain text, yes on the way in. You still escape on the way out.
Where can I learn more?
The official WordPress developer handbook has a section on plugin security and data validation. It’s the best source.
Related reading
- Writing a WordPress plugin with AI: the minimum viable plugin
- Building a WordPress plugin with AI: the workflow that works
- Building a simple membership area with AI help
Open the last plugin you wrote or had written. How many echo lines are escaped?