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.

What is the best way to add/remove items for the wp_nav_menu() based on user roles?

For instance a custom menu that looks like:

  • Some Page
  • Some Other Page
  • Special Admin Page

Where the Special Admin Page should only be visible for admin users.

Is this best done with wp_nav_menu_items filter or do I need a custom Walker?

This is a possible duplicate of: Hide menu items for visitors and filter based on role but that doesn't appear to have been completely solved. Though it does mention a tutorial about a custom Walker that seems relevant.

EDIT:

Based on Toscho's answer and How to add a custom field in the advanced menu properties? I combined the two to form my own plugin

Nav Menu Roles

Fair warning that I cannot vouch for its speed and I am relatively certain that it will not work with another custom Walker, but it was a one-day plugin.

share|improve this question

1 Answer 1

up vote 0 down vote accepted

Create a custom walker. Redefine the method start_el() only:

function start_el( &$output, $item, $depth, $args )
{
    if ( 'Your secret item title' !== $item->title 
        or current_user_can( 'administrator' ) 
    )
    {
        parent::start_el( &$output, $item, $depth, $args );
    }
}

Please mind that this is just pseudo code. I can not give it a test at the moment.

share|improve this answer
    
Great, thanks. I don't think you can pass a role name to current_user_can() though. I wish you could though. On another note is there a way to add some checkboxes to the advanced menu options (along w/ description, etc)? Doesn't look like it, but if there was I could wrap this into a plugin. –  helgatheviking Sep 15 '12 at 12:48
    
current_user_can() accepts role names too, it is just poorly named. And no, there is still no hook to add more fields to menu items. JavaScript might be an option to insert those. –  toscho Sep 15 '12 at 12:52
    
Gotcha. It is marked in the codex as not working perfectly with role name, which is why I thought that. Can I rely on Javascript? Ie, the menu drag and drop already does rely on Javascript so I can assume that most customizing the menu will have Javascript running? –  helgatheviking Sep 15 '12 at 13:08
    
No, you cannot. :) Menus can be created and edited without JavaScript. –  toscho Sep 15 '12 at 13:12
    
I did find this: wordpress.stackexchange.com/questions/33342/… which is pretty close. –  helgatheviking Sep 15 '12 at 13:55

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.