Created
July 18, 2023 14:27
-
-
Save johanguse/afe5c3ecf7eea75ca234ed9007b4b075 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