Add attribute to script loaded by the theme

I was looking for a method to add the data-cfasync=”false” attribute to a javascript loaded by the theme itself.

My theme load the script

<script type="e350ac6f596d90da70624b6d-text/javascript" src='https://thegroovecartel.com/wp-content/themes/zeen/assets/js/jquery.fluidbox.min.js?ver=2.0.5' id='jquery-fluidbox-js'>

And I would like to have

<script data-cfasync="false" type="e350ac6f596d90da70624b6d-text/javascript" src='https://thegroovecartel.com/wp-content/themes/zeen/assets/js/jquery.fluidbox.min.js?ver=2.0.5' id='jquery-fluidbox-js'>

Basically just the inclusion of my attribute letting everything unchanged

The script is loaded by the theme with

wp_enqueue_script( 'jquery-fluidbox', get_parent_theme_file_uri( 'assets/js/jquery.fluidbox.min.js' ), array(), '2.0.5', true );

I’ve seen this solution Adding Additional Attributes in Script Tag for 3rd party JS but it’s 7 years old and doesn’t seem to work for me.

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

The code referenced in your question is still good. I double checked, and this worked for me:

function wpse_script_loader_tag( $tag, $handle ) {
    if ( 'jquery-fluidbox' !== $handle ) {
        return $tag;
    }

    return str_replace( ' src', ' data-cfasync="false" src', $tag );
}
add_filter( 'script_loader_tag', 'wpse_script_loader_tag', 10, 2 );

(I tested with a different script handle, but that won’t matter):
Add attribute to script loaded by the theme


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