I'm trying to use the wp_register_script and wp_enqueue_script FUNCTION on WordPress to enqueue a script, which has two attributes: "integrity" and "crossorigin".
Normally I use PHP and my code looks like:
wp_register_script('jquery', 'http' . ($_SERVER['SERVER_PORT'] == 443 ? 's' : '') . '://code.jquery.com/jquery-3.1.1.slim.min.js', false, null);
wp_enqueue_script('jquery');
With any other script. The wp_register_script takes five parameters (in this case four) $handle, $src, $deps, $ver ($media). I'm wondering where I can add the two attributes. I've already tried:
wp_register_script('jquery', 'http' . ($_SERVER['SERVER_PORT'] == 443 ? 's' : '') . '://code.jquery.com/jquery-3.1.1.slim.min.js'.'integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n"', false, null);
wp_enqueue_script('jquery');
But it didn't work.
Anyone who had the same problem? This is the original script from bootstrap 4, which also has bootstrap and tether with the same attributes (integrity and crossorigin) so, since it is pretty new, any kind of help will be very appreciated.
You can use the script_loader_tag hook (the main part is actually not my code, but I honestly don't remember where I got it, probably somewhere here on SO or WP Stack Exchange):
add_filter( 'script_loader_tag', 'add_attribs_to_scripts', 10, 3 );
function add_attribs_to_scripts( $tag, $handle, $src ) {
// The handles of the enqueued scripts we want to defer
$async_scripts = array(
'jquery-migrate',
'sharethis',
);
$defer_scripts = array(
'contact-form-7',
'jquery-form',
'wpdm-bootstrap',
'frontjs',
'jquery-choosen',
'fancybox',
'jquery-colorbox',
'search'
);
$jquery = array(
'jquery'
);
if ( in_array( $handle, $defer_scripts ) ) {
return '<script src="' . $src . '" defer="defer" type="text/javascript"></script>' . "\n";
}
if ( in_array( $handle, $async_scripts ) ) {
return '<script src="' . $src . '" async="async" type="text/javascript"></script>' . "\n";
}
if ( in_array( $handle, $jquery ) ) {
return '<script src="' . $src . '" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous" type="text/javascript"></script>' . "\n";
}
return $tag;
}