Question

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/core@2.9.1/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');
Was it helpful?

Solution

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/core@2.9.1/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
);
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top