Blog

How To Find Out The Handle For Enqueued WordPress Scripts

With the wide variety of plugins and themes out there for WordPress websites, sometimes you can run into issues with the scripts and styles they include. It could be your new form plugin has some hideous styles, or maybe a couple of different plugins are all enqueuing different versions of the select2 library causing all sorts of issues.

In these situations, you likely want to remove the offending scripts. The scripts can be removed with wp_dequeue_script for JavaScript files and wp_dequeue_style for CSS files by passing the handle of the script to the relevant function. Finding the handle for stylesheets is relatively easy, as WordPress adds an id attribute to the link element that includes the stylesheet, but it doesn’t do the same for Javascript files.

Thankfully this can be changed. By adding the below code to your functions.php file or in a custom plugin, each script’s handle will be added to a data attribute. This applies both on the front end and in the admin.

<?php
add_filter( 'script_loader_tag', 'cameronjonesweb_add_script_handle', 10, 3 );
function cameronjonesweb_add_script_handle( $tag, $handle, $src ) {
return str_replace( '<script', sprintf(
'<script data-handle="%1$s"',
esc_attr( $handle )
), $tag );
}

Once you’ve implemented the above code, your scripts will all have a data-handle attribute containing the script’s handle, as shown in the screenshot below.

Enqueued scripts with the handle displayed in a data attribute

Now you can retrieve the script’s handle from the data-handle attribute to pass to wp_dequeue_script.

Did you find this post useful?

YesNo