Get the list of enqueued scripts in wordpress?

2020-07-11 10:03发布

问题:

I would like to know how to get the list of scripts enqueued in wordpress via wp_enqueue_script. I have done some research and checked the wp core itself but the closest I can get is something like:

add_options_page('Wp Sysinfo', 'Wp Sysinfo', 'manage_options', 'wp-sysinfo', 'sysinfo_page');

function sysinfo_page(){
    global $wp_scripts;
    print_r($wp_scripts->queue);
}

However it only show scripts in the admin pages not the front end.

FYI: Im building a plugin to display system information in wordpress. This is to provide plugin/theme authors useful info to troubleshoot problems reported by users.

Edit:

In short, I need a way to get all scripts and styles enqueued in both admin and frontend, and view them within a custom admin page.

回答1:

There is a dedicated Wordpress action hook for styles as well as scripts. These hooks will be triggered after every script or style is enqueued:

function inspect_scripts() {
    global $wp_scripts;
    print_r($wp_scripts->queue);
}
add_action( 'wp_print_scripts', 'inspect_scripts' );

function inspect_styles() {
    global $wp_styles;
    print_r($wp_styles->queue);
}
add_action( 'wp_print_styles', 'inspect_styles' );


回答2:

When I did <?php global $wp_scripts; var_dump($wp_scripts->queue); ?> on the index.php page of the standard 2014 Wordpress theme it showed me non-admin scripts that were being queued. If you just do var_dump on the $wp_scripts variable itself you'll get lots of scripts, I am guessing all the scripts in the theme or something like that.

So if you are only showing this info to the site administrator then it should be fine just to echo it out like at the bottom of the page. I used a memory profiling plugin once (it showed me load times/memory loads used by various plugins) and it put that information at the bottom of the page, it was pretty useful.

But like the comments say if you are only displaying the queued scripts then in the wp-admin area that is only the admin scripts, on the front end you'll get more.