Enqueue scripts & styles responsibly
So you have a fancy plugin that’s doing something awesome on a WordPress admin page. The plugin needs some CSS and/or JS to work so you enqueue them in the admin_enqueue_scripts
hook. All good™. Hmm, not really. What you did is correct, but not very responsible. The fact is, I rarely see plugins that do their stuff on all admin pages, so why enqueue the scripts and/or styles everywhere?
Here’s a simple trick to make a plugin enqueue its scripts & styles only on certain admin pages.
Let’s say we have a plugin that enhances the new and edit post screens:
/**
* Enqueue admin script on new and edit post screens.
*/
function myplugin_enqueue_admin_scripts() {
wp_enqueue_script(
'myplugin-admin-script',
plugin_dir_url( __FILE__ ) . 'script.js',
array( 'jquery' ),
'0.1.0',
true
);
}
add_action( 'load-post.php', 'myplugin_enqueue_admin_scripts' );
add_action( 'load-post-new.php', 'myplugin_enqueue_admin_scripts' );
Notice that we’re not using the admin_enqueue_scripts
hook? That’s the trick! Instead, we’re using the load-(page)
hook so that our script will only load on those pages.
Further Reading
load-(page)
at the Codex.
Posted on in Tips & Tutorials.