Skip to content

Instantly share code, notes, and snippets.

@johanguse
Created July 18, 2023 14:27
Show Gist options
  • Save johanguse/afe5c3ecf7eea75ca234ed9007b4b075 to your computer and use it in GitHub Desktop.
Save johanguse/afe5c3ecf7eea75ca234ed9007b4b075 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