How to easily load assets on custom WordPress admin pages

February 10, 2014

There are many plugins for WordPress that add functionality to the wp-admin area. These plugins often load additional assets such as CSS or Javascript. Polite developers will save resources and ensure those assets only load on the intended page.

When you add a page to wp-admin with

add_menu_page()

or

add_submenu_page()

it returns a hook name. When the newly created page loads WordPress will fire an action with the hook name prefixed by ‘load-‘. This hook will be used to queue the assets to load.

Add the page and the determine the hook name:

$hook = add_submenu_page( 'tools.php', 'My Custom Submenu Page', 'My Custom Submenu Page', 'manage_options', 'my-custom-submenu-page', 'my_custom_submenu_page_callback' );

Tap into the hook to load the assets:

add_action( "load-$hook", 'my_custom_submenu_asset_loader' );

Putting it all together (with an example from the Codex) you get:

add_action('admin_menu', 'register_my_custom_submenu_page');

function register_my_custom_submenu_page() {
   $hook = add_submenu_page( 'tools.php', 'My Custom Submenu Page', 'My Custom Submenu Page', 'manage_options', 'my-custom-submenu-page', 'my_custom_submenu_page_callback' );

    add_action( "load-$hook", 'my_custom_submenu_asset_loader' );
}

function my_custom_submenu_page_callback() {
    echo '
'; echo '

My Custom Submenu Page

'; echo '
'; } function my_custom_submenu_asset_loader() { // Load in CSS and Javascript here }
Leave a Reply

Your email address will not be published. Required fields are marked *