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:https:\/\/dadadasdad.com\/wp-content\/plugins\/woocommerce-some-gateway\/assets\/images};
/script
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.
Edit/Explanation: The answer mentioned here: How do I add custom attributes to javascript tags in Wordpress? does not apply to this question as that answer is showing how to add an extra attribute to script tags that are loading external scripts with src
. But wp_localize_script()
adds internal javascript and not points to any external javascript. The clean_url
approach shown in the answer can also be done using script_loader_tag
if you know the handle of the script.
But please note here we are looking for a way to add an extra attribute to internal scripts added via wp_localize_script()
which doesn't have any src
attribute to it.
Topic wp-localize-script wp-enqueue-script hooks Wordpress javascript
Category Web