Security PHP Advanced

Add a Content Security Policy in Report-Only Mode

Send a starter Content Security Policy that reports what it would block without breaking anything, so you can tighten it safely.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 16 lines
add_action( 'send_headers', function (): void {
	$policy = [
		"default-src 'self'",
		"script-src 'self' 'unsafe-inline'",
		"style-src 'self' 'unsafe-inline'",
		"img-src 'self' data: https:",
		"font-src 'self' data:",
		"connect-src 'self'",
		"frame-src 'self' https://www.youtube.com https://player.vimeo.com",
		"frame-ancestors 'self'",
		"base-uri 'self'",
		"form-action 'self'",
		"object-src 'none'",
	];
	header( 'Content-Security-Policy-Report-Only: ' . implode( '; ', $policy ) );
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

A Content Security Policy (CSP) tells browsers which sources a page may load scripts, styles, images and frames from. It’s one of the strongest defences against cross-site scripting, but a wrong policy breaks your site. Report-only mode lets you test a policy without enforcing it.

How it works

On send_headers, the snippet sends a Content-Security-Policy-Report-Only header with a starter policy: only your own domain for scripts, styles, fonts and connections, images from anywhere over HTTPS, embeds from YouTube and Vimeo, and no plugins or framing by other sites.

Browsers don’t block anything in report-only mode. They list each violation in the DevTools console instead, so you can see which outside sources your site really uses.

Things to watch

  • Open the console on your main page types (home, a post, the shop, checkout) and add each legitimate source the console reports, such as your analytics or payment provider.
  • When the console is clean, change the header name to Content-Security-Policy to enforce it. Test checkout carefully afterwards.
  • The policy allows inline scripts and styles because WordPress and most plugins use them. Removing 'unsafe-inline' needs nonces on every inline script, which is a bigger project.

How to test it

Open your homepage with DevTools open. The Network panel should show the header on the page response, and the console should list any “[Report Only]” violations.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only