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.

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


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' ) ) {
    $wp_admin_bar->add_menu( /* ... */ );
  • Just so I'm understanding if the function will not execute is there even a point in adding it? – m-torin May 19 '11 at 15:12
  • 1
    @MTaylor: In my first snippet, the current_user_can() will be called too early (the user object has not been initialized). In my second snippet it will be called when the admin bar is being set up, and at this time the user object exists, so you can use current_user_can(). So it will be called in both situations, but just a bit later, which is what you need. – Jan Fabry May 19 '11 at 15:20

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;

// 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
  • Using if ( current_user_can('capability') ) shows the menu item regardless of the capability. – m-torin May 19 '11 at 15:20

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.