Seb
Posted on March 26, 2020
How To Enqueue Wordpress Plugin Admin Scripts Only Where You Need Them
If you're building a Wordpress plugin with an admin panel, only enqueue your scripts/styles on your page
On of my pet peeves with Wordpress plugins is intrusive scripts and styles. They're the biggest contributor to big, slow Wordpress sites, and they give Wordpress a bad name.
When I'm building a plugin with an admin panel, I like to only enqueue my scripts and styles on that page.
Here's how I do it;
1. First, create your admin page
<?php
add\_action('admin\_menu', 'nwd\_add\_admin\_page');
function nwd\_add\_admin\_page() {
// add top level menu page
add\_menu\_page(
'My Admin Page',
'My Admin Page',
'manage\_options',
'my-admin-page',
'admin\_page\_html'
)
}
This code will add a top level menu item 'My Admin Page', which will display the HTML returned by the callback 'admin_page_html'
You may also want to create a submenu page which will be slightly different code.
2. Enqueue your scripts and styles cleverly
<?php
add\_action('admin\_enqueue\_scripts', 'nwd\_admin\_enqueue\_scripts');
public function nwd\_admin\_enqueue\_scripts($screen) {
// Check the $screen variable to see what page we're on
// if you created a top level page in the previous step
// $screen should be toplevel\_page\_$slug
// If $screen doesn't match, we will quit so we don't
// pollute the whole admin with our scripts/styles
// Quit if it's not our screen
if('toplevel\_page\_my-admin-page' !== $screen) return;
// If we get this far, it must be our screen
// Enqueue our assets
wp\_enqueue\_script('my-admin-page', plugin\_dir\_url( \_\_FILE\_\_ ) . 'assets/js/admin.js', array(), null, true);
}
This code is how you're probably already adding scripts, but the small difference is we check the $screen variable to see if we are on the right screen.
Wordpress will pass the $screen variable in when it calls your enqueue scripts function, and you can use this to check which admin page you're on.
Clever!
Posted on March 26, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.