1

I just googled this but didn`t retrieve any specific info. I have such code on a PHP template for WordPress:

<?php wp_enqueue_script( 'jquery-carousel', get_template_directory_uri().'/js/jquery.carouFredSel-6.2.1-packed.js', array('jquery'),'',true); ?>

And I want to add CloudFlare ignore for Rocketloader data-cfasync="false" just before the 'src' attribute of jquery.carouFredSel-6.2.1-packed.js

What can I do?

Regards

Edit:

A big thanks to @Mary for the code. So the solution for this is to add this function in functions.php :

function add_data_attribute( $tag, $handle, $src ) {
    if ( 'jquery-carousel' !== $handle )
       return $tag;

    return str_replace( ' src', ' data-cfasync="false" src', $tag );
}

add_filter( 'script_loader_tag', 'add_data_attribute', 10, 3 );

If there is a need to add more tags like 'jquery-carousel1', 'jquery-carousel2' to this function, the code looks like this:

function add_data_attribute( $tag, $handle, $src ) {
    if( ! in_array( $handle, array( 'jquery-carousel', 'jquery-carousel1', 'jquery-carousel2' ) ) )
       return $tag;

    return str_replace( 'src', 'data-cfasync="false" src', $tag );
}

add_filter( 'script_loader_tag', 'add_data_attribute', 10, 3 );
twelvell
  • 257
  • 1
  • 8
  • 19

1 Answers1

2

You could try filtering with script_loader_tag.

function add_data_attribute( $tag, $handle, $src ) {
    if ( 'jquery-carousel' !== $handle )
       return $tag;

    return str_replace( ' src', ' data-cfasync="false" src', $tag );
}

add_filter( 'script_loader_tag', 'add_data_attribute', 10, 3 );

This way you can target your specific enqueued script.

Mary
  • 96
  • 6
  • Thanks Mary, this really helped me. – twelvell Mar 19 '17 at 22:03
  • One more thing is if I want to add more to the list - how can I edit the if ( 'jquery-carousel' !==$handle ) and add here also others like - 'jquery-ui-script' and 'jquery-tools-forms-script' ? How do I add multiple tags there? – twelvell Mar 19 '17 at 23:55
  • You could condition if the handle doesn't exists in an array of handles. `if( ! in_array( $handle, array( 'jquery-ui-script', 'jquery-tools-forms-script' ) ) )` – Mary Mar 20 '17 at 00:22
  • Thank you for helping out, this worked! I will update the function for others to see it. – twelvell Mar 20 '17 at 00:36