How do I only load a plugin js on it’s settings pages?

You need to use a plugin page-specific script enqueue hook.

Edit

Best-practice method is to use admin_enqueue_scripts-{hook}, rather than admin_print_scirpts-{hook}. But, because you’re targeting your own Plugin’s admin page specifically, either one is perfectly fine.

The hook to avoid is the “global” admin_print_scripts.

Original

The call would look like this:

    /* Using registered $page handle to hook script load */
    add_action('admin_print_scripts-' . $page, 'my_plugin_admin_scripts');

And you define the $page hook like so:

$page = add_submenu_page( $args );

Answer copied directly out of the Codex:

<?php
add_action( 'admin_init', 'my_plugin_admin_init' );
add_action( 'admin_menu', 'my_plugin_admin_menu' );

function my_plugin_admin_init() {
    /* Register our script. */
    wp_register_script( 'my-plugin-script', plugins_url('/script.js', __FILE__) );
}

function my_plugin_admin_menu() {
    /* Register our plugin page */
    $page = add_submenu_page( 'edit.php', // The parent page of this menu
                              __( 'My Plugin', 'myPlugin' ), // The Menu Title
                              __( 'My Plugin', 'myPlugin' ), // The Page title
              'manage_options', // The capability required for access to this item
              'my_plugin-options', // the slug to use for the page in the URL
                              'my_plugin_manage_menu' // The function to call to render the page
                           );

    /* Using registered $page handle to hook script load */
    add_action('admin_print_scripts-' . $page, 'my_plugin_admin_scripts');
}

function my_plugin_admin_scripts() {
    /*
     * It will be called only on your plugin admin page, enqueue our script here
     */
    wp_enqueue_script( 'my-plugin-script' );
}

function my_plugin_manage_menu() {
    /* Output our admin page */
}
?>

Leave a Comment