1

I have tried following the codex following various threads here, simple, copy-paste various examples but to no avail. It just doesn't work.

Has it been depreciated? Has anyone got this to work in any recent version of WP or 5.7 specifically

 function my_scripts() {
wp_enqueue_script( 'bs-popper', 'https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js', array('jquery'), _S_VERSION, true );
wp_script_add_data('bs-popper' , array('integrity') , array('sha384-XXXXXXXXXXXXXXXX')); 
} 
add_action( 'wp_enqueue_scripts', 'my_scripts' ); 

[EDIT] Simple: Above example was from a version that had more than one but this simple one doesn't work either

wp_script_add_data('bs-popper' , 'integrity' , 'sha384-XXXXXXX');

2 Answers 2

2

This is not what wp_script_add_data() does.

It doesn't support adding arbitrary attributes to the script tag. It lets you add metadata to the enqueued script, but out of the box the only key that WordPress supports is 'conditional', which is used for telling the script whether to load in certain versions of IE. For example, this:

wp_script_add_data('bs-popper' , 'conditional' , 'IE 9');

Will result in this:

<!--[if IE 9]>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" id="bs-popper-js">
<![endif]-->

But this:

wp_script_add_data('bs-popper' , 'attribute' , 'value');

Won't do anything.

If you want to be able to add attributes to scripts that way, you need to use the script_loader_tag filter to filter the HTML of the <script> tag to add the attribute if the data has been added with wp_script_add_data(). There's an example of that here, but for your use case it would look like this:

add_filter(
    'script_loader_tag', 
    function( $tag, $handle ) {
        $integrity = wp_scripts()->get_data( $handle, 'integrity' );

        if ( $integrity ) {
            $tag = str_replace( '></', ' integrity="'. esc_attr( $integrity ) .'"></', $tag );
        }

        return $tag;
    }, 
    10, 
    2
);
1
  • That worked Thanks: For multiple I just added another one in the same function, it worked but is that the way to go?
    – D Flexer
    May 6, 2021 at 14:58
2

Introduced in WP 5.7.0 (a few months before this post), the wp_script_attributes filter can be used to add arbitrary attributes.

Example:

add_filter( 'wp_script_attributes', static function ( array $attr ) : array {
    if ( 'bs-popper-js' !== $attr['id'] ) {
        return $attr;
    }

    $attr['integrity'] = 'sha384-XXXXXXX';

    return $attr;
} );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.