Skip to content

Instantly share code, notes, and snippets.

@beastycoding
Forked from johanguse/nonce.php
Created July 14, 2024 20:13
Show Gist options
  • Save beastycoding/1db0e06821a5ae8cacc5f7aaa0001eb6 to your computer and use it in GitHub Desktop.
Save beastycoding/1db0e06821a5ae8cacc5f7aaa0001eb6 to your computer and use it in GitHub Desktop.
Add nonce to script and styles on WordPress
add_action( 'template_redirect', function () {
ob_start( function ( $output ) {
$nonces = [];
$output = preg_replace_callback( '#<script.*?\>#', function ( $matches ) use ( &$nonces ) {
$nonce = wp_create_nonce( $matches[0] );
$nonces[] = $nonce;
return str_replace( '<script', "<script nonce='{$nonce}'", $matches[0] );
}, $output );
$output = preg_replace_callback( '#<style.*?\>#', function ( $matches ) use ( &$nonces ) {
$nonce = wp_create_nonce( $matches[0] );
$nonces[] = $nonce;
return str_replace( '<style', "<style nonce='{$nonce}'", $matches[0] );
}, $output );
$nonces_csp = array_reduce( $nonces, function ( $header, $nonce ) {
return "{$header} 'nonce-{$nonce}'";
}, '' );
header( sprintf( "Content-Security-Policy: base-uri 'self'; form-action 'self'; object-src 'none'; script-src https:%s 'strict-dynamic'", $nonces_csp ) );
return $output;
} );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment