Enqueue script in specific page

Inside admin-header.php, there’s the following set of hooks:

do_action('admin_enqueue_scripts', $hook_suffix);
do_action("admin_print_styles-$hook_suffix");
do_action('admin_print_styles');
do_action("admin_print_scripts-$hook_suffix");
do_action('admin_print_scripts');
do_action("admin_head-$hook_suffix");
do_action('admin_head');

The one to always use it admin_enqueue_scripts, both for stylesheet and scripts. More info in this answer.

It has one additional argument, the $hook_suffix. This argument is exactly the same as the return value that you get from add_submenu_page() and the related (shorthand) functions.

Example

Note: The following example assumes that you already registered the script previously, so it’s available with the handle/identifier of your_handle.

add_action( 'admin_enqueue_scripts', 'wpse113509_register_script' );
function wpse113509_register_script( $hook_suffix )
{
    if ( 'dashboard.php' !== $hook_suffix )
        return;

    wp_enqueue_script( 'your_handle' );
}

Additional Notes

As I see that you’re identifying the Themes root directory using get_option('template_directory'), I have to leave a short additional note as this isn’t how it’s done nowadays, as this info then comes from the DB, which want to avoid. It as well will ignore the default filters that are in place for that:

  • get_template_directory()Path to the parent theme root dir
  • get_stylesheet_directory()Path to the child theme root dir
  • get_template_directory_uri()URL to the parent theme root dir
  • get_stylesheet_directory_uri()URL to the child theme root dir
  • plugin_dir_path( __FILE___ ) – Root of the current file, no matter if in child/parent theme or a plugin. Trailing slashed result.

Then there’s wp_get_theme(), which calls an instance of WP_Theme for the currently active theme.

$current_theme = wp_get_theme();
$current_theme->get_theme_root();
$current_theme->get_template();
$current_theme->get_template_directory();

If you got a child theme, you can as well simply call $current_theme->parent() to access all the other WP_Theme methods on the parent themes instance. For e.g.

$current_theme->parent()->get_theme_root();

This then also allows to access header information from the theme. For e.g. the Name, DomainPath, etc.

Leave a Comment