Content Security Policy Header (Report-Only)
Sends a starter Content Security Policy in report-only mode, so you can see in the browser console what a strict policy would block before enforcing it.
Opens WPIDE on
Code
// Adjust the sources to the services your site uses, then switch $wpide_csp_enforce to true.
$wpide_csp = array(
"default-src 'self'",
"script-src 'self' 'unsafe-inline' https://www.googletagmanager.com",
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
"font-src 'self' data: https://fonts.gstatic.com",
"img-src 'self' data: https:",
"connect-src 'self' https://www.google-analytics.com",
"frame-src 'self' https://www.youtube.com https://player.vimeo.com",
"frame-ancestors 'self'",
"base-uri 'self'",
"form-action 'self'",
"object-src 'none'",
);
$wpide_csp_enforce = false;
add_action( 'send_headers', function () use ( $wpide_csp, $wpide_csp_enforce ) {
if ( headers_sent() || is_user_logged_in() ) {
return; // Logged-in users load editor and admin bar assets the policy may not cover.
}
header( ( $wpide_csp_enforce ? 'Content-Security-Policy: ' : 'Content-Security-Policy-Report-Only: ' ) . implode( '; ', $wpide_csp ) );
} );
Notes
Test page by page with the browser console open; an enforced policy that is too strict breaks scripts, embeds and fonts.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.