Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.