How to show a admin bar menu item only to users with certain capabilities?

I’m trying to add items to the admin bar but only for users with certain capabilities, such as add_movies in a plugin. The problem is that, according to @toscho and @TheDeadMedic, the plugin executes its code too early in the order of operations to use current_user_can.

I tried using if ($user->has_cap('add_movies')) but get Fatal error: Call to a member function has_cap() on a non-object in xxx.

Read More

Am I missing an obvious global or is the solution more complicated?

Related posts

Leave a Reply

2 comments

  1. The check will be called too early if you just write it in your plugin file like this:

    if ( current_user_can( 'add_movies' ) ) {
        add_action( 'admin_bar_menu', 'wpse17689_admin_bar_menu' );
    }
    function wpse17689_admin_bar_menu( &$wp_admin_bar )
    {
        $wp_admin_bar->add_menu( /* ... */ );
    }
    

    Because it will execute when your plugins is loaded, which is very early in the startup process.

    What you should do is always add the action, but then in the callback for the action check for current_user_can(). If you can’t do the action, just return without adding the menu item.

    add_action( 'admin_bar_menu', 'wpse17689_admin_bar_menu' );
    function wpse17689_admin_bar_menu( &$wp_admin_bar )
    {
        if ( ! current_user_can( 'add_movies' ) ) {
            return;
        }
        $wp_admin_bar->add_menu( /* ... */ );
    }
    
  2. Try it with if ( current_user_can('capability') ) : /* your code */; endif;

    EDIT: Haven’t read your Q completely. Have you tried the following?

    global $current_user;
    get_currentuserinfo();
    
    // Here you can start interacting with everything the current user has:
    echo '<pre>';
        print_r($current_user); // show what we got to offer
    echo '</pre>';
    
    // Then you'll have to do something with the role to get the caps and match against them