Subresource Integrity for Scripts and Styles From CDNs
Adds integrity and crossorigin attributes to the CDN-hosted scripts and stylesheets you list, so browsers refuse to run them if the CDN copy is ever tampered with.
Opens WPIDE on
Code
// Handle => integrity hash of the exact file that handle loads.
$wpide_sri_hashes = array(
'example-cdn-script' => 'sha384-REPLACE_WITH_THE_FILE_HASH',
);
$wpide_add_sri = function ( $tag, $handle ) use ( $wpide_sri_hashes ) {
if ( empty( $wpide_sri_hashes[ $handle ] ) || false !== strpos( $tag, 'integrity=' ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
return $tag;
}
$tags = new WP_HTML_Tag_Processor( $tag );
while ( $tags->next_tag() ) {
if ( in_array( $tags->get_tag(), array( 'SCRIPT', 'LINK' ), true ) && ( $tags->get_attribute( 'src' ) || $tags->get_attribute( 'href' ) ) ) {
$tags->set_attribute( 'integrity', $wpide_sri_hashes[ $handle ] );
$tags->set_attribute( 'crossorigin', 'anonymous' );
break;
}
}
return $tags->get_updated_html();
};
add_filter( 'script_loader_tag', $wpide_add_sri, 20, 2 );
add_filter( 'style_loader_tag', $wpide_add_sri, 20, 2 );
Notes
Get the hash for each exact file version from the CDN (for example the "Copy SRI" button on cdnjs) and update it whenever you change the version.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.