Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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