1

I want to use the defer attribute for scripts. I understand this can be done using script_loader_tag. However I also want consistent versioning of the files as some plugins do not do it properly.

How do I find scripts' versioning when I use

add_filter( 'script_loader_tag', …

using their handles?

1

Use the $wp_scripts, which is a global variable to get the version of a registered script.

add_filter( 'script_loader_tag', 'script_handler', 10, 3 );
function script_handler( $tag, $handle, $src ) {
  // the following global contains all the information you need
  global $wp_scripts;
  $ver = $wp_scripts->registered[ $handle ]->ver;

  // do your thing
}

Note, this is exemplary.

| improve this answer | |
  • Thanks. Doesn't this need "for each"? Also my problem is that some plugins don't register the correct version in wp_enqueue_scripts, so will this recover the correct version? – Ramanan Dec 25 '16 at 14:25
  • @Ramanan No, it doesn't need a for each, $handle is a string. script_loader_tag applies to every script separately. This will recover the version the script is registered with, so no. Unless you know exactly where the correct version is saved I see no possibility to retrieve it, because WordPress doesn't know anything about the actual version, it knows just the one given to it when registering the script. – Nicolai Dec 25 '16 at 14:40
  • Thanks again. Can't I use get_plugin_data? codex.wordpress.org/Function_Reference/get_plugin_data. It seems to take the filepath as input. My basic problem is: get all the scripts in any page, add the defer attribute and version them correctly. – Ramanan Dec 25 '16 at 14:52
  • @Ramanan Sure, you can use get_plugin_data. I assumed you want the version of the script of the javascript file you're loading. – Nicolai Dec 25 '16 at 15:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.