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.

If I want to always change the admin toolbar at the top of the page it's easy.

add_action('admin_bar_menu', 'add_toolbar_items', 100);
function add_toolbar_items($admin_bar){
  $admin_bar->add_menu( array(
    'id'    => 'my-item',
    'title' => 'My Item',
    'href'  => '#',
    'meta'  => array(
        'title' => __('My Item'),            
    ),
  ));
}

No problem. I want to add something to the top of the page, but only when we are on my plugin page.

So I want to do something like this:

add_action('admin_menu', 'my_plugin_menu');
function my_plugin_menu(){
  //We add the hook for our menu item on the main menu
  $main = add_menu_page( 'My Swell Plugin', 'My Swell Plugin', 'edit_posts', 'blah', 'generate_main_page',,__FILE__));
}
function generate_main_page(){
  //We are definitely in our plugins page now - let's modify the admin toolbar.
  add_action('admin_bar_menu', 'add_toolbar_items', 100);
  require_once('mainwindow.php');
}
share|improve this question

2 Answers 2

up vote 1 down vote accepted

You need to remember screen id of your page and check current screen id before adding new menu item:

add_action( 'admin_menu', 'my_plugin_menu' );
function my_plugin_menu() {
    global $my_swell_plugin_page;
    $my_swell_plugin_page = add_menu_page( 'My Swell Plugin', 'My Swell Plugin', 'edit_posts', 'blah', 'generate_main_page' );
}

function generate_main_page() {
    //We are definitely in our plugins page now - let's modify the admin toolbar.
}

add_action( 'admin_bar_menu', 'add_toolbar_items', 100 );
function add_toolbar_items( $admin_bar ) {
    global $my_swell_plugin_page;

    if ( $my_swell_plugin_page == get_current_screen()->id ) {
        $admin_bar->add_menu( array(
            'id' => 'my-item',
            'title' => 'My Item',
            'href' => '#',
            'meta' => array(
                'title' => __( 'My Item' ),
            ),
        ) );
    }
}
share|improve this answer

Maybe the $current_screen object can help you:

global $current_screen;
if ( $current_screen->base == 'toplevel_page_blah' ){
    add_action('admin_bar_menu', 'add_toolbar_items', 100);
}

I haven't tested it but it should do the trick.

share|improve this answer

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.