# Nonce-Based Content Security Policy for Scripts

> Adds a fresh random nonce to every script WordPress prints and sends a strict, nonce-based script policy (report-only by default), the modern way to block injected scripts.

- Type: PHP
- Runs: Frontend only
- Category: [Security](https://wpide.com/library/category/security/)
- Tags: csp, headers, scripts
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/sec-csp-script-nonces/

## Code

```php
// Switch to true to enforce the policy once nothing legitimate is reported.
$wpide_nonce_enforce = false;

$wpide_csp_nonce = function () {
    static $nonce = null;

    if ( null === $nonce ) {
        $nonce = rtrim( strtr( base64_encode( random_bytes( 18 ) ), '+/', '-_' ), '=' );
    }

    return $nonce;
};

$wpide_add_nonce = function ( $attributes ) use ( $wpide_csp_nonce ) {
    if ( is_array( $attributes ) && ! isset( $attributes['nonce'] ) ) {
        $attributes['nonce'] = $wpide_csp_nonce();
    }

    return $attributes;
};

add_filter( 'wp_script_attributes', $wpide_add_nonce );
add_filter( 'wp_inline_script_attributes', $wpide_add_nonce );

add_action( 'send_headers', function () use ( $wpide_csp_nonce, $wpide_nonce_enforce ) {
    if ( headers_sent() ) {
        return;
    }

    $policy = sprintf( "script-src 'nonce-%s' 'strict-dynamic' https: 'unsafe-inline'; object-src 'none'; base-uri 'self'", $wpide_csp_nonce() );
    header( ( $wpide_nonce_enforce ? 'Content-Security-Policy: ' : 'Content-Security-Policy-Report-Only: ' ) . $policy );
} );
```

## Notes

Scripts hard-coded into theme templates do not get the nonce and full-page caches reuse it, so check the console with your cache active before setting $wpide_nonce_enforce to true.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Nonce-Based Content Security Policy for Scripts" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
