Dev Tip #2: How to Load Scripts Only on a Specific Admin Page

When building a plugin, loading your scripts and styles everywhere in the WordPress admin isn’t ideal.
It adds unnecessary bloat and slows things down.

Here’s how I load my JS or CSS files only on the plugin settings page (or any specific admin page).

The Snippet

add_action( 'admin_enqueue_scripts', function( $hook ) {
    if ( $hook !== 'settings_page_my-plugin-slug' ) {
        return;
    }

    wp_enqueue_script(
        'my-plugin-script',
        plugin_dir_url( __FILE__ ) . 'assets/admin.js',
        [ 'jquery' ],
        '1.0',
        true
    );

    wp_enqueue_style(
        'my-plugin-style',
        plugin_dir_url( __FILE__ ) . 'assets/admin.css',
        [],
        '1.0'
    );
});

How It Works

  • $hook is passed by WordPress to tell you what admin page is currently being loaded.
  • settings_page_my-plugin-slug is the ID of your plugin settings page (you get this from the slug used in add_options_page() or add_menu_page()).
  • If you return early, your scripts won’t load anywhere else.

Bonus Tip

You can error_log( $hook ); on any admin page to quickly find the correct page slug during development. Super handy.


Why This Matters

This keeps your plugin lightweight, improves performance, and avoids accidentally breaking unrelated parts of the admin area with your scripts.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *