-
-
Save beastycoding/1db0e06821a5ae8cacc5f7aaa0001eb6 to your computer and use it in GitHub Desktop.
Add nonce to script and styles on WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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