![]()
A missing or overly broad Content Security Policy (CSP) can leave a WordPress site more exposed to unwanted content, while a policy that is too strict can break scripts, forms, embeds, or even administration tools. A practical WordPress CSP Plugin can help you address both risks: build a policy around the resources your site actually uses, begin in Report-Only mode, review violations, and enforce it only after testing. There is no universally safe policy to copy; your theme, plugins, and third-party services determine which sources your directives need.
Before changing response headers, prepare a staging environment and identify how your site serves and caches pages. Nonce-based policies require the nonce in the response header to match the nonce in the rendered HTML, so page caches and CDNs need particular attention.
- PHP 8.0+ and WordPress 6.3+; WordPress 6.3+ provides the
wp_inline_script_attributeshook used in this guide. - A staging site and a recent backup.
- HTTPS enabled and permission to install or edit a small custom plugin.
- Browser developer tools, especially the Console and Network panels.
- An inventory of your themes, plugins, CDN, analytics, fonts, embeds, payment tools, and other external services.
- Awareness of any full-page cache, reverse proxy, or CDN that may cache HTML or response headers.
Inventory the Site Sources Before Writing a Policy
Start by auditing real site behavior, not by copying a policy from another WordPress installation. Review representative public pages, login and administration screens, search, forms, embedded media, and checkout or membership flows where applicable. Include logged-in and logged-out views: plugins often load different assets depending on the user or action.
Map First-Party and Third-Party Requests
In your browser’s Network panel, inspect requests and note each origin, resource type, affected page or feature, and whether it is essential. Track scripts, styles, images, fonts, frames, and connections, including assets loaded only after a click. Separate files you control from third-party services; an observed host is not automatically trustworthy. Also identify inline scripts and markup generated by themes or plugins, since they may need a deliberate nonce or other compatibility strategy.
Choose Directives and a Reporting Strategy
Map each required source to the directive that governs it: script-src, style-src, img-src, font-src, connect-src, and frame-src. Consider restrictive foundations such as default-src, base-uri, object-src, and frame-ancestors, then add only audited requirements. The inventory will guide a Report-Only policy, which reports violations without blocking resources while you test.

Map First-Party and Third-Party Requests
Use the Network panel to create a source inventory from real page activity. Enable Preserve log, reload representative pages, and exercise interactive features such as opening a menu, submitting a form, or loading an embed. For each request, record its origin, resource type, page or feature, and whether the feature depends on it. Include the scheme, hostname, and nonstandard port when present; a hostname alone may not describe the actual source precisely.
- First-party: Identify assets served by your WordPress host, subdomains, or CDN, and confirm which ones your site controls.
- Third-party: Record services such as analytics, payment providers, fonts, video, and API endpoints. Verify that each is necessary before considering it for the policy.
- Not visible as requests: Inspect rendered markup for inline scripts and styles. Note scripts injected by themes or plugins, and resources that appear only after a user action.
Map each essential resource to its relevant directive, such as script-src, img-src, or connect-src. Keep the inventory as a reviewed allowlist with a reason for every external origin; do not add a host merely to silence a browser message.
Choose Directives and a Reporting Strategy
Use the inventory to choose a small set of directives, rather than adding every host the browser happens to request. Begin with restrictive foundations such as default-src 'self', object-src 'none', and base-uri 'self'. Set frame-ancestors deliberately: use 'none' if the site must not be embedded, or an appropriate trusted source if embedding is required. This directive does not inherit from default-src.
Add resource directives only when your audit shows they are needed. For example, list verified script origins under script-src, image origins under img-src, and API or analytics endpoints under connect-src. Apply the same narrow approach to style-src, font-src, and frame-src. Do not treat a starter policy as universally safe; theme output, plugin features, and third-party integrations vary between sites.
Begin observation with the Content-Security-Policy-Report-Only response header. It lets the browser report policy violations without blocking the affected resources, so you can test real workflows and refine the directives. By contrast, Content-Security-Policy enforces the policy and can block disallowed content. A reporting destination is not automatic; configure one separately if you need server-side reports.
Build a WordPress CSP Plugin in Report-Only Mode
A small custom plugin gives you a reviewable, version-controlled place to manage the policy without assuming that a generic WordPress CSP Plugin will account for your theme, plugins, or caching setup. Start on staging and treat this policy as a test baseline, not a universal production configuration: add external origins only after your inventory confirms they are needed.
Create the Plugin and Set the Report-Only Header
Create wp-content/plugins/pnet-csp-report-only/pnet-csp-report-only.php, add the code below, and activate the plugin on staging. The wp_headers filter adds a Report-Only response header; the browser reports violations but does not block the affected resources.
<?php
/**
* Plugin Name: PixelNet CSP Report Only
* Description: Sends a starter Content Security Policy in Report-Only mode.
* Version: 1.0.0
*/
function pnet_add_csp_report_only_header($headers) {
$policy = "default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-src 'self'";
$headers['Content-Security-Policy-Report-Only'] = $policy;
return $headers;
}
add_filter('wp_headers', 'pnet_add_csp_report_only_header');
[/code]
<p>Adjust each directive to match reviewed site requirements: for example, add a verified image host to <code>img-src</code> or an API origin to <code>connect-src</code>. Do not add a broad wildcard to clear a violation. After activation, use the browser Network panel to inspect a page response and confirm the exact header name and value. Before relying on this plugin, check whether the web server, a security plugin, or your CDN already sends CSP headers; multiple policies can interact and produce unexpected results.</p>
<figure id="attachment_12225" aria-describedby="caption-attachment-12225" style="width: 850px" class="wp-caption aligncenter"><img decoding="async" src="https://cdn.pixelnet.in/wp-content/uploads/2026/12/01071407/WordPress-CSP-Plugin-Header-Review-850x364.webp" alt="WordPress CSP Plugin - Header Review" width="850" height="364" class="size-postcontent wp-image-12225 pnet-loaded"><figcaption id="caption-attachment-12225" class="wp-caption-text">Header Review</figcaption></figure>
<h3 id="create-report-only-header">Create the Plugin and Set the Report-Only Header</h3>
<p>On your staging site, create a small plugin directory such as <code>wp-content/plugins/pnet-csp-report-only/</code> and place the plugin PHP file inside it. Give the file a valid WordPress plugin header, then activate it from the Plugins screen. Keeping this change in a custom plugin rather than a theme makes it easier to preserve, review, and deploy independently of theme updates.</p>
<p>The callback attached to <code>wp_headers</code> should add the <code>Content-Security-Policy-Report-Only</code> entry to the response-header array and return that array. Adjust directive values to match the source inventory; do not treat the initial policy as a universal allowlist. WordPress provides a reference for the <a href="https://developer.wordpress.org/reference/hooks/wp_headers/" target="_blank" rel="noopener">wp_headers filter</a>.</p>
<p>After activation, open a representative page and use Developer Tools → Network to select its main document request. Check Response Headers for the exact <code>Content-Security-Policy-Report-Only</code> name and confirm that the value matches the policy you intended. This mode reports violations without blocking resources. If the header is absent or unexpected, check PHP errors and inspect whether the web server, security plugin, reverse proxy, or CDN is adding or changing CSP headers. Verify the response visitors actually receive, not only the plugin code.</p>
<div class="pn-contextual-link">
<i class="fa-sharp fa-light fa-lightbulb-on pn-icon" aria-hidden="true"> </i>
<p class="d-inline m-0"><strong>Did you know:</strong> You can significantly boost your site's security and prevent malicious DDoS amplification attacks when you <a href="https://www.pixelnet.in/blog/disable-xml-rpc-in-wordpress/" title="Disable XML-RPC In WordPress: Boost Security In 4 Simple Steps" contenteditable="false" style="cursor: pointer;">disable xml-rpc in wordpress</a> using a simple code snippet directly inside your active theme's functions file?</p>
</div>
<h2 id="add-script-nonces">Add Matching Nonces to WordPress Scripts</h2>
<p>A nonce lets the browser allow a specific script element under your policy without permitting every inline script. Generate it once per response, then use that same value in both the CSP header and eligible script tags. Replace the previous Report-Only header callback with this updated plugin code; it retains Report-Only mode while adding nonce support.</p>
[code lang='php']
<?php
/**
* Plugin Name: PixelNet CSP Report Only
* Description: Sends a nonce-aware CSP in Report-Only mode.
* Version: 1.1.0
*/
function pnet_csp_nonce() {
static $nonce = null;
if ($nonce === null) {
$nonce = base64_encode(random_bytes(18));
}
return $nonce;
}
function pnet_add_csp_report_only_header($headers) {
$policy = "default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; script-src 'self' 'nonce-" . pnet_csp_nonce() . "'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-src 'self'";
$headers['Content-Security-Policy-Report-Only'] = $policy;
return $headers;
}
add_filter('wp_headers', 'pnet_add_csp_report_only_header');
function pnet_add_nonce_to_script_tag($tag, $handle, $src) {
if (preg_match('/\snonce\s*=/i', $tag)) {
return $tag;
}
return preg_replace('/^<script\b/', '<script nonce="' . esc_attr(pnet_csp_nonce()) . '"', $tag, 1);
}
add_filter('script_loader_tag', 'pnet_add_nonce_to_script_tag', 10, 3);
function pnet_add_nonce_to_inline_script_attributes($attributes) {
$attributes['nonce'] = pnet_csp_nonce();
return $attributes;
}
add_filter('wp_inline_script_attributes', 'pnet_add_nonce_to_inline_script_attributes');
[/code]
<h3 id="nonce-script-types">Nonce Enqueued and Inline Scripts</h3>
<p><code>script_loader_tag</code> adds the nonce to script elements printed by WordPress for enqueued scripts. The inline-attributes filter covers WordPress inline script output; see the official <a href="https://developer.wordpress.org/reference/hooks/wp_inline_script_attributes/" target="_blank" rel="noopener">wp_inline_script_attributes reference</a>. This hook requires WordPress 6.3 or later. Check theme and plugin output in the rendered page: arbitrary markup or scripts inserted outside these hooks are not covered automatically. A header and element with different nonce values will not match, so the browser can block the script.</p>
<h3 id="nonce-script-types">Nonce Enqueued and Inline Scripts</h3>
<p>The two hooks cover different WordPress script output paths. <code>script_loader_tag</code> filters the HTML tag for an enqueued script, allowing the plugin to add the nonce to that element. <code>wp_inline_script_attributes</code> adds attributes to inline script elements generated through WordPress APIs. It is available in WordPress 6.3 and later. Both hooks must call the same nonce helper used to build the response header; otherwise, the browser sees a mismatch and the script is not authorized by the nonce.</p>
<p>These hooks do not cover every possible script. Themes or plugins may print raw script markup, add elements through JavaScript, or use output paths that bypass WordPress script APIs. Test the rendered HTML and browser behavior across public pages, administration screens, and important plugin workflows. Keep <code>script-src</code> limited to the nonce and reviewed origins; do not add a wildcard or trust an unknown host to silence a violation. If an audit confirms that legacy inline scripts need <code>'unsafe-inline'</code>, treat it only as a temporary compatibility concession: it weakens script protection and should be removed when those scripts can be updated. Script nonces also do not authorize inline styles or style attributes, which need a separate strategy.</p>
<h3 id="handle-cache-and-styles">Handle Styles, Caching, and Response Scope</h3>
<p>Handle styles separately from scripts. A nonce in <code>script-src</code> does not authorize inline style elements or style attributes. Prefer moving inline styles into enqueued files; if inline styles are necessary, choose a deliberate <code>style-src</code> strategy and test each output type. Do not add <code>'unsafe-inline'</code> by default to silence style violations, since it weakens the policy.</p>
<p>Full-page caching can undermine nonce matching. A cache might serve HTML containing one nonce while the response header contains another, causing legitimate scripts to fail. Replaying the same nonce across responses also defeats its per-response purpose. Bypass caching for nonce-bearing HTML, or use an edge-layer approach that injects the same fresh nonce into both the HTML and header. Confirm this works through the actual production path, including CDN and page-cache layers.</p>
<p>Inspect the delivered response, not just the WordPress plugin output: compare the nonce in the response header with the rendered script tags, and test cache hits as well as misses. Also check public and logged-in pages, since different response paths or cache rules may affect their headers.</p>
[pnet_info_box type="warning" title="For Developers"]Do not enable nonce-based enforcement until you have verified header and HTML matching on the live delivery path, including cached responses.[/pnet_info_box]
<h2 id="inspect-csp-violations">Inspect Report-Only Violations and Refine the Policy</h2>
<p>A <code>Content-Security-Policy-Report-Only</code> header lets the browser report policy violations without blocking the requested resources. Use this observation phase on staging first, then monitor representative production traffic if appropriate. Open Developer Tools and review Console messages alongside Network requests: the Console identifies the violated directive, while the request details help reveal the resource origin and page behavior involved. A reporting endpoint is not created automatically; configure a reporting destination separately if you need server-side reports, and test that destination independently.</p>
<h3 id="test-critical-journeys">Test Critical Site Journeys</h3>
<p>Exercise public pages, login, <code>wp-admin</code>, search, forms, embeds, media, and relevant checkout or membership flows. Repeat tests while logged in and logged out, and check mobile layouts as well as desktop. Record each violation with its affected feature, directive, origin, proposed action, and retest result. This makes the review repeatable and helps distinguish a genuine site dependency from an unused or unexpected request.</p>
<h3 id="resolve-violations">Resolve Violations Without Broad Allowlisting</h3>
<p>For each message, identify what initiated the request before changing the policy. Remove an unnecessary dependency where possible; otherwise, add only a verified, required origin to the directive that governs that resource type. Do not add wildcards or broad unsafe directives simply to quiet the Console. Retest the same journeys after each meaningful adjustment and confirm that unrelated sources remain restricted.</p>
<figure id="attachment_12226" aria-describedby="caption-attachment-12226" style="width: 850px" class="wp-caption aligncenter"><img decoding="async" src="https://cdn.pixelnet.in/wp-content/uploads/2026/12/01071413/WordPress-CSP-Plugin-Violation-Review-850x364.webp" alt="WordPress CSP Plugin - Violation Review" width="850" height="364" class="size-postcontent wp-image-12226 pnet-loaded"><figcaption id="caption-attachment-12226" class="wp-caption-text">Violation Review</figcaption></figure>
<h3 id="test-site-journeys">Test Critical Site Journeys</h3>
<p>Turn the audit into a repeatable acceptance test rather than checking only the homepage. Use a staging copy with the Report-Only header active, open the browser Console and Network panels, and complete the workflows visitors and staff rely on. Keep the policy unchanged during each test run so you can compare results consistently.</p>
<p>Cover the site’s applicable journeys, including:</p>
<ul>
<li>Log in and out, navigate menus, and use search.</li>
<li>Submit key forms and confirm validation, confirmation messages, and any related network requests.</li>
<li>Load embeds and media, and exercise checkout, membership, or account flows where relevant.</li>
<li>Repeat on desktop and mobile, both logged in and logged out; include relevant WordPress administration tasks.</li>
</ul>
<p>For every CSP violation, record the page and feature, the resource origin, the directive named in the browser message, and the proposed action. After changing a directive or integration, repeat the affected journey and note whether the violation disappeared and the feature still works. Keep unresolved items visible rather than broadly allowing a source to make the test appear clean.</p>
<h3 id="resolve-csp-violations">Resolve Violations Without Broad Allowlisting</h3>
<p>Use each Report-Only message as a clue to investigate a specific feature, not as an instruction to trust the reported source. Identify the affected page and action, inspect the request in the Network panel, and confirm which resource type and origin are involved. Then decide whether the request is legitimate and necessary.</p>
<p>Choose the narrowest safe fix:</p>
<ul>
<li>Remove an unused script, embed, or integration when the site no longer needs it.</li>
<li>Correct a plugin or theme integration that is loading an asset from an unexpected location.</li>
<li>If a verified service is required, add its exact origin only to the directive that controls that resource, such as <code>script-src</code> for scripts or <code>connect-src</code> for API requests.</li>
<li>For inline-code violations, assess nonce coverage or refactor the code; do not default to <code>'unsafe-inline'</code>.</li>
</ul>
<p>Avoid wildcards and broad sources such as <code>*</code> merely to clear Console warnings. After each meaningful change, repeat the same critical journey and confirm that the feature works, the violation is resolved, and unrelated sources remain restricted. Keep a brief record of the reason for each allowed origin so future plugin or service changes can be reviewed deliberately.</p>
<div class="pn-contextual-link">
<i class="fa-sharp fa-light fa-lightbulb-on pn-icon" aria-hidden="true"> </i>
<p class="d-inline m-0"><strong>Did you know:</strong> Implementing proper <a href="https://www.pixelnet.in/blog/wordpress-ajax-security/" title="WordPress AJAX Security: The Ultimate Guide to Safely Verifying Nonces (2026)" contenteditable="false" style="cursor: pointer;">WordPress AJAX security</a> can prevent disastrous CSRF attacks and safely protect your database from unauthorized frontend requests?</p>
</div>
<h2 id="enforce-csp">Enforce CSP Gradually and Monitor Production</h2>
<p>Switch to enforcement only after you have investigated Report-Only violations and confirmed that essential visitor and administrator workflows pass. Change the response header name from <code>Content-Security-Policy-Report-Only</code> to <code>Content-Security-Policy</code>. Keep your audited directives and trusted origins; do not use this transition to broaden the policy.</p>
<p>Replace the existing header callback with the version below, retaining the nonce helper and script-attribute hooks from the previous step. Deploy to staging first, inspect the delivered response header, and repeat critical tests. Then release to a monitored production group or a low-traffic window and check the same workflows. If legitimate content is blocked, restore Report-Only mode or disable the custom plugin, then investigate before trying enforcement again.</p>
[code lang='php']
function pnet_add_csp_enforced_header($headers) {
$policy = "default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; script-src 'self' 'nonce-" . pnet_csp_nonce() . "'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-src 'self'";
$headers['Content-Security-Policy'] = $policy;
return $headers;
}
add_filter('wp_headers', 'pnet_add_csp_enforced_header');
Use the exact policy you validated, including any narrowly approved origins. Save the previous working version so rollback is quick and controlled.
Pro Tip
You might also like:
Roll Out, Recheck, and Keep the Policy Current
Treat rollout as the start of maintenance, not the finish line. After enforcing the policy, verify the actual response header and matching nonce in rendered script tags on both cache hits and misses. Repeat critical visitor and administrator journeys, and check the browser Console for new violations. Include logged-in and logged-out sessions because their pages may load different assets.
Keep a copy of the last known-good policy in version control or another controlled change log. For every external origin, record the service that needs it, the directive that permits it, the pages or features that use it, and the reason it is trusted. This makes later reviews safer than relying on memory and gives you a clear rollback point if an integration changes unexpectedly.
Retest after theme or plugin updates, analytics changes, payment-provider changes, and CDN or cache configuration changes. These can introduce new request origins or alter nonce delivery without an obvious visual failure. Repeat the same documented test journeys, then add only verified requirements and confirm that unrelated sources remain restricted.
A WordPress CSP Plugin is an ongoing, site-specific control—not a one-time setting that guarantees every future integration will work.
Common Errors
When a feature fails after adding CSP, diagnose the specific response and resource before changing the policy. Browser Console messages identify the violated directive; the Network panel helps confirm the request origin and whether caching or another header is involved.
- A script is blocked despite having a nonce: Compare the nonce in the response header with the value on the rendered script element. They must match for that response. Confirm the script uses a WordPress output hook covered by the nonce code; raw markup or scripts injected outside those hooks may be missed.
- Failures happen intermittently: Compare HTML and header nonces on both cache hits and misses. A page cache or CDN may replay HTML with a stale nonce or serve a header generated with a different value. Adjust the cache path before enforcing the policy.
- Violations persist: Check the exact directive and resource origin, then determine whether the request is necessary. Add only a verified origin to the relevant directive. Do not resolve errors by allowing
*or adding'unsafe-inline'broadly. - The policy is unexpectedly strict: Inspect the delivered response for CSP headers added by the web server, CDN, security plugin, and custom plugin. Multiple policies can apply together; remove or reconcile unintended duplicates.
- Inline styles or admin tools break: A script nonce does not authorize inline styles. Choose and test a separate styles strategy. For a broken administrator or plugin workflow, restore Report-Only mode or the saved policy, isolate the affected action, and make a narrow correction before retesting.
You might also like:
Conclusion
A missing or overly broad CSP can increase exposure to unwanted content, while a policy that is too strict can disrupt essential WordPress features. The safe approach is incremental: inventory the site’s real resource origins, add a small site-specific plugin, issue a Report-Only header, and add matching nonces to supported script output. Test key visitor and administrator workflows, investigate each violation, and enforce the reviewed policy only after the site behaves as expected.
Before and after rollout, verify the response header and rendered HTML through the actual delivery path, including cache hits, CDN behavior, and third-party integrations. Keep a tested rollback policy, and repeat the audit after meaningful theme, plugin, or service changes. A carefully maintained WordPress CSP Plugin is most useful when its directives reflect your site’s requirements rather than a generic template.