wordpress get url of registered script

Viewed 1205

If I register a script or style (using wp_register_script() or wp_register_style()), is there a way I can get the URL of that script/style?

(If you must know why, I'm trying to put those URL's into another function that generates prefetch link tags so I can prefetch certain scripts/styles for a performance boost in my site.)

2 Answers

Just in case someone is still looking for this:

<?php
function invdr_get_script_uri_by_handler( $handler ){
    //Get an instance of WP_Scripts or create new;
    $wp_scripts = wp_scripts(); 

    //Get the script by registered handler name
    $script = $wp_scripts->registered[ $handler ]; 

    if ( file_exists( ABSPATH . $script->src ) ){
        return ABSPATH . $script->src;
    }
    return false;
}
add_action( 'wp_enqueue_scripts', 'invdr_get_script_uri_by_handler', PHP_INT_MAX );

Tested in wordpress 5.0

You can use wp_scripts() to get the instance of the WP_Scripts class which contains the registered scripts (this class extends WP_Dependencies).

Basically, try looking in:

$wp_scripts = wp_scripts();
var_dump( $wp_scripts->registered );
var_dump( $wp_scripts );
Related