How do I add a javascript file to all admin pages via a plugin?

Context: For logged in users, I’m appending a query string to the url so that it will bypass Cloudflare’s cache. So, example.com becomes example.com/?nocache=y, for example.

I accomplished this pretty easily with the following code:

function tbcloudflare_query_arg() {   
if(is_user_logged_in()){
        wp_enqueue_script( 'tbcloudflare_check_query', plugin_dir_url( __FILE__ ) . 'js/tbcloudflare.js', array('jquery'), '1.0' );
     }
 }
 add_action('wp_enqueue_scripts', 'tbcloudflare_query_arg');

I can see the file in the source, and it works great on the front end pages, but not the back end of course. So, I tried:

function tbcloudflare_admin_query_arg($hook){
    wp_enqueue_script( 'tbcloudflare_check_query', plugin_dir_url( __FILE__ ) . 'js/tbcloudflare.js', array('jquery'), '1.0' );
}
add_action('admin_enqueue_scripts', 'tbcloudflare_admin_query_arg' );

This question has been asked before in various forms, and the above code structure is straight from many of the examples. But I can’t get it to work in 4.7.2.

This has to be loaded from a plugin rather than a functions.php file. What could I be doing wrong? The code does not show up in the html source or show that it’s loaded through Chrome’s inspect source.

1 Answer
1

The Plugin Developer Handbook recommends using plugins_url() to create the URL to the JS file. Try using that function inside your script loader, and using a different handle for the script depending on the context (like prefixing the admin script name with “admin-“) to avoid conflicting script registration.

Alternatively, you can register the script just once, and enqueue it when needed on the enqueue hooks.

Leave a Comment