Skip to content

Instantly share code, notes, and snippets.

@leek
Created April 2, 2021 05:44
Show Gist options
  • Save leek/cdace8839b247b770d91728aa53b93fc to your computer and use it in GitHub Desktop.
Save leek/cdace8839b247b770d91728aa53b93fc to your computer and use it in GitHub Desktop.
Add SRI attribute to WordPress scripts and stylesheets.
<?php
/**
* Add SRI attributes to external JS resources
*/
function add_sri_attribute($tag, $handle, $src = null)
{
$known_hashes = array(
'https://code.jquery.com/jquery-1.12.4.min.js' => 'sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=',
);
if (!is_ssl() || empty($known_hashes[$src])) {
return $tag;
}
// Append a proper SRI attribute to an element's attribute list.
$sri_att = ' crossorigin="anonymous" integrity="' . $known_hashes[$src] . '"';
$insertion_pos = strpos($tag, '>');
return substr($tag, 0, $insertion_pos) . $sri_att . substr($tag, $insertion_pos);
}
add_filter('style_loader_tag', 'add_sri_attribute', 999999, 3);
add_filter('script_loader_tag', 'add_sri_attribute', 999999, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment