I don't yet understand why, but according to Codex, you should only use admin_enqueue_scripts
to enqueue styles/scripts in the admin. I have an open Question asking why, but haven't yet received a satisfactory answer. The Codex entry might be in reference to this core dev's post.
Here's how to do it the "correct" way (note: the admin_enqueue_scripts
hook should only be called from another hooked function, e.g., as I've done in the second code block with admin_menu
. If you try to hook admin_enqueue_scripts
too early, you'll get errors):
add_action('admin_enqueue_scripts', 'YOUR_ENQUEUEING_FUNCTION');
function YOUR_ENQUEUEING_FUNCTION($hook_suffix) {
global $my_menu_hook_akt;
// exit function if not on my own options page!
// $my_menu_hook_akt is generated when creating the options page, e.g.,
// $my_menu_hook_akt = add_menu_page(...), add_submenu_page(...), etc
if ($hook_suffix != $my_menu_hook_akt) return;
$handle = 'my_js';
wp_register_script($handle, 'http://example.com/path/to/my-javascript.js');
wp_enqueue_script($handle);
} // function YOUR_ENQUEUEING_FUNCTION
Below is a fully functional plugin to play around with; it does nothing except inject your javascript file into the <head> of only your options page -
<?php
// Plugin Name:0-Menu Test
global $my_menu_hook_akt;
add_action('admin_menu', 'create_menu_akt');
function create_menu_akt() {
global $my_menu_hook_akt;
$my_menu_hook_akt = add_menu_page(
'My Cool Plugin\'s Title',
'My Cool Plugin\'s Name',
'manage_options',
'my-cool-plugins-slug',
'draw_options_page_akt'
);
add_action('admin_enqueue_scripts', 'enqueue_only_on_my_page_akt');
} // function create_menu_akt
function enqueue_only_on_my_page_akt($hook_suffix) {
global $my_menu_hook_akt;
// exit function if not on my own options page!
// $my_menu_hook_akt is generated when creating the options page, e.g.,
// $my_menu_hook_akt = add_menu_page(...), add_submenu_page(...), etc
if ($hook_suffix != $my_menu_hook_akt) return;
$handle = 'my_js';
wp_register_script($handle, 'http://example.com/path/to/my-javascript.js');
wp_enqueue_script($handle);
} // function enqueue_only_on_my_page_akt
function draw_options_page_akt() {
// draw your options page
} // function draw_options_page_akt