有几种方法可以仅将脚本添加到某些管理页面。在我看来,最好的选择是admin_enqueue_scripts
并使用$hook
参数:
add_action(\'admin_enqueue_scripts\', \'cyb_admin_scripts\');
function cyb_admin_scripts( $hook ) {
//You may need adjustment here to match for page
//If the URL of your page is admin.php?page=psbg, the hook
// to check would be toplevel_page_psbg
if( $hook == \'toplevel_page_my-page-slug\' ) {
wp_register_script(\'my-script\', plugins_url() . \'/my-plugin/js/script.js\', array(\'jquery\'));
wp_register_style(\'my-style\', plugins_url() . \'/my-plugin/css/style.css\');
wp_enqueue_style(\'my-style\');
wp_enqueue_script( \'my-script\');
}
}
我经常看到的另一种常见方式是使用
load-page action 将文件排队。例如:
//Adding the menu in admin area
add_action(\'admin_menu\', \'cyb_add_menu\');
function cyb_add_menu(){
$hook_suffix = add_menu_page(__(\'Page title\'), __(\'Menu title\'), \'manage_options\', \'my-page-slug\', \'display_callback_fn\');
// Call to cyb_settings_page_load() when our page is loaded
add_action( \'load-\'. $hook_suffix, \'cyb_settings_page_load\' );
}
function cyb_settings_page_load() {
//Enqueue styles and scripts
wp_enqueue_script(\'my-script\', plugins_url() . \'/my-plugin/js/script.js\', array(\'jquery\'));
wp_enqueue_style(\'my-style\', plugins_url() . \'/my-plugin/css/style.css\');
}
function display_callback_fn() {
//Build your page hiere
}