Skip to content

Instantly share code, notes, and snippets.

@otakupahp
Last active November 8, 2021 23:58
Show Gist options
  • Save otakupahp/b4025ef167eb41ae7f9fafbb0dc66362 to your computer and use it in GitHub Desktop.
Save otakupahp/b4025ef167eb41ae7f9fafbb0dc66362 to your computer and use it in GitHub Desktop.
Adds support for 'integrity' and 'crossorigin' at enqueuing a script on WordPress
<?php
/**
* Adds support for 'integrity' and 'crossorigin'
*
* This relies on the function *wp_script_add_data* been called when enqueuing the script
*
* @param $tag
* @param $handle
*
* @return string
*/
function filter_script_loader_tag( $tag, $handle ) {
foreach ( array('integrity','crossorigin') as $attr ) {
if ( $value = wp_scripts()->get_data( $handle, $attr ) ) {
$extra = sprintf( '<script %s="%s"', $attr, $value );
$tag = str_replace('<script', $extra, $tag);
}
}
return $tag;
}
@otakupahp
Copy link
Author

Usage example:

wp_register_script( 'my-script', 'https://example.com', array(), '', true );
wp_script_add_data( 'my-script', 'integrity', 'sha384-toSKN4vyRFOcxd3Bzjj/AoOwY+Rg0G0fw54EGlWWeA4z3dyJ' );
wp_script_add_data( 'my-script', 'crossorigin', 'anonymous' );
wp_enqueue_script( 'my-script' );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment