我还不明白为什么,但是according to Codex, 您应该只使用admin_enqueue_scripts
将样式/脚本排入管理队列。我有一个open Question 询问原因,但尚未得到满意的答复。Codex条目可能参考this core dev\'s post.
以下是如何以“正确”的方式进行操作(注意:admin_enqueue_scripts
钩子只能从另一个钩子函数调用,例如,正如我在第二个代码块中使用admin_menu
. 如果你想勾引admin_enqueue_scripts
太早,您将收到错误):
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
下面是一个功能齐全的插件;它除了将javascript文件注入到<;仅限选项页的页眉
<?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