How to enqueue javascript files properly in the WordPress admin panel

You’d probably have answered the question already, won’t you? We all know that the correct answer is to do that we have to write a function that hooks the “admin_enqueue_scripts” and inside that function we will have to load the script via wp_enqueue_scripts() function. That’s the correct answer, but when it comes to the best practices, it fails. Because when you’re loading a javascript file blindly in all pages, it can be messy and it also may conflict with other scripts which are already loaded in that page. Besides that, why load an extra script everywhere when you actually need it in a specific page, or two perhaps.

The correct, or “precise” way to enqueue a javascript file in the WordPress admin panel is to check first which page you’re on. And when you’re on that specific page where this javascript file is actually required, load it. So how you’re gonna check which page you’re on in the admin panel? The enqueue hook passes a parameter that tells you about this. Let’s have a look at the following example

[sourcecode language=”php”]
add_action("admin_enqueue_scripts","admin_scripts_loader");

function admin_scripts_loader(){
wp_enqueue_script("myscript","path/to/my/script.js");
}
[/sourcecode]

There is nothing wrong with the enqueueing system above. However, the only problem is that it will load your script in every admin page, you need it or not. So let’s write a better version of that admin_scripts_loader function.

[sourcecode language=”php”]
function admin_scripts_loader($hook){
if(in_array($hook,array("post-new.php","post.php","edit.php"))) {
//specifically load this javascript in post editor pages
wp_enqueue_script("myscript", "path/to/my/script.js");
}
}
[/sourcecode]

Now the code is more accurately loading your javascript file only in the post editor pages. This $hook variable gives you the name of the PHP file that you’re on. So it’s quite easy for you to figure out where you should load it.

Hope you enjoyed it.