How to add extra attributes to the script tag added via wp_localize_script()


So, wp_localize_script() are awesome to add custom data to a script. And these data gets added to the HTML like:

<script id='woocommerce_some-js-extra' type="text/javascript">
var wc_some_params = {"key":"sdfsfsdfs","use_iframes":"1","images_dir":""};

This is all good. But the problem is that if I want to add an extra attribute to the script tag and instead of showing it like this:

<script id='woocommerce_some-js-extra' type="text/javascript">

if I want to show it like this:

<script id='woocommerce_some-js-extra' data-cfasync="false" type="text/javascript">

This is where I am facing the problem. I really see no way to add the extra data-cfasync="false" attribute to that inline script tag. Initially, I tried to use script_loader_tag filter but the problem is that when I am doing the following:

add_filter( 'script_loader_tag', function( $tag, $handle ) {
    if( $handle === 'woocommerce_somesubmit' ) {
    return str_replace( ' type', ' data-cfasync="false" type', $tag );
  } else {
    return $tag;
}, 10, 2 );

It is pointing to the script added via wp_enqueue_script() and not pointing to the inline script added via wp_localize_script(). So, instead of adding that attribute to the inline script, it is adding the attribute to the script tag with src in it.

I was wondering if anyone knows any hooks or filter to add/modify the script tag added via wp_localize_script(). I searched a lot and even checked the WordPress core codes but still couldn’t figure out a way for this. Also, there is no similar questions I have found for this issue.
Any help will be highly appreciated.

, , , iSaumya 2 years 2020-09-02T04:10:32-05:00 0 Answers 68 views 0

Leave an answer