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 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?

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

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( /* ... */ );
}
share|improve this answer
    
Just so I'm understanding if the function will not execute is there even a point in adding it? –  mattrepublic 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
add comment

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
share|improve this answer
    
Using if ( current_user_can('capability') ) shows the menu item regardless of the capability. –  mattrepublic May 19 '11 at 15:20
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.