0

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');
}
1

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' ),
            ),
        ) );
    }
}
1

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.

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.