Enqueue Wordpress Plugin Admin Panel Scripts

ST

Seb Toombs

Oct 21 2019 ()

1 min read

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!