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

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