How do I Enqueue styles/scripts on Certain /wp-admin Pages?

I have two simple functions that load stuff using wp_enqueue_style() and wp_enqueue_script(), something like these:

function admin_custom_css()
{ wp_enqueue_style( 'stylesheet_name', 'stylesheet.css') }; 

function admin_custom_js 
{ wp_enqueue_script( 'javascript_file', 'script.js') };

… and a few admin pages, created with add_menu_page() and add_submenu_page()

function my_menu() {
   add_menu_page('Page 1', 'bar', 'something', 'else', 'foo');
   add_submenu_page( 'theme_menu', 'Subpage 1', 'Subpage', 'something', 'else', 'foo'); 
add_action('admin_menu', 'my_menu'); 

How do I load my two functions only on these pages?

Right now I’m using:

add_action('admin_init', 'admin_custom_css' ); 
add_action('admin_init', 'admin_custom_js' );  

But it loads my files on every admin page, which is not nice at all.

Can I do this via one simple line in functions.php or have to enqueue them within my pages separately (I prefer the first option strongly, since I’d have to edit a lot of admin-page-creating-functions).



add_menu_page and add_submenu_page both return the page’s “hook suffix”, which can be used to identify the page with certain hooks. As such, you can use that suffix in combination with the variable hooks admin_print_styles-{$hook_suffix} and admin_print_scripts-{$hook_suffix} to specifically target these pages.

function my_menu() {
   $menu = add_menu_page( 'Page 1', 'bar', 'something', 'else', 'foo' );
   $submenu = add_submenu_page( 'theme_menu', 'Subpage 1', 'Subpage', 'something', 'else', 'foo' );

   add_action( 'admin_print_styles-' . $menu, 'admin_custom_css' );
   add_action( 'admin_print_styles-' . $submenu, 'admin_custom_css' );

   add_action( 'admin_print_scripts-' . $menu, 'admin_custom_js' );
   add_action( 'admin_print_scripts-' . $submenu, 'admin_custom_js' );

I find this to be a clean method for adding all of this because it’s all handled within the one function. If you decide to remove this functionality, simply remove the call to the one function.

Leave a Comment