The right hooks
// Use both for scripts & styles *)
wp_enqueue_scripts // (for the frontend)
login_enqueue_scripts // (for the login screen)
admin_enqueue_scripts // (for the admin dashboard)
*) Read this article @wpdevel.
Further reading in the Codex about the three hooks
On the admin_enqueue_scripts
hook, you have an argument as well: The $hook_suffix
:
add_action( 'admin_enqueue_scripts', function( $hook )
{
var_dump( $hook );
} );
Admin page hooks
When registering a admin (sub)menu page, you can save the result, which is the page hook, into a variable:
function register_admin_page()
{
// Register (sub)menu page
$hook_suffix = add_submenu_page( $your_args_array );
// Add styles to hook
add_action( "load-{$hook_suffix}", 'callback_function' );
}
// Use one of those hooks to register the page
add_action( 'admin_menu', 'register_admin_page' );
add_action( 'user_admin_menu', 'register_admin_page' );
add_action( 'network_admin_menu', 'register_admin_page' );
// Register your styles & scripts in here
function callback_function()
{
// do stuff
}
Admin globally available variables to check against
The following
global $hook_suffix, $typenow, $pagenow, $self, $parent_file, $submenu_file
are available on a wide range of admin pages. Use them to check if you're on the requested page that you need and only then do stuff.
// Example
if ( 'edit.php' !== $GLOBALS['pagenow'] )
return;
Even better than testing against a variable, which can get reset on the fly (example) ...
$GLOBALS['wp'] = array( 'lost', 'my', 'contents', );
... is using the \WP_Screen
object on admin pages:
add_action( 'admin_enqueue_scripts', function( $hook )
{
/** @var \WP_Screen $screen */
$screen = get_current_screen();
var_dump( $screen );
if ( 'post.php' !== $screen->base )
return;
} );