wp_script_add_data doesn’t seem to work

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/<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="41222e332401736f786f70">[email protected]</a>/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');

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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/<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff9c908d9abfcdd1c6d1ce">[email protected]</a>/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
);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x