0

I'm working on a plugin and want to restrict some things to my plugin-specific admin menu pages only. Therefore, I write the slugs being returned when adding (sub)menu pages into an array so I can check later on the current page against it.

The problem seems to be that get_current_screen is returning null when called from/before admin_init. I add the menu pages, however, hooked to admin_menu - which is before admin_init.

Here is the not working code:

add_action( 'admin_menu', 'my_admin_menu' );
function my_admin_menu() {
    // Set up plugin admin menu
    $menu_pages = array();
    $menu_pages[] = add_menu_page( ... );
    $menu_pages[] = add_submenu_page( ... );

    $screen = get_current_screen(); // UNFORTUNATELY, $screen is null here
    $screen = $screen->id;
    foreach ( $menu_pages as $page ) if ( $screen === $page ) {
        // Do plugin-specific stuff
    }
} // function my_admin_menu

So, do I really have to store the pages array in a way that I can access it later in a function hooked somewhere after admin_init? I thought about just using the page slugs where I defined the pages and then forget about it.

As toscho pointed out, one may use the slugs as hooks (what they actually are):

$page = add_menu_page( ... );
add_action( $page, ... );

However, when in need of the current screen, that hook is located too early in the chain, so one could/should use add_action( 'load-' . $page, ...); instead.

1

The slug returned by add_menu_page() is the name of an action.

foreach ( $menu_pages as $action )
    add_action( $action, "callback_handler" );

See the comments in my demo plugin T5 Admin Menu Demo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.