Hide Menu items base on capability

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.

1 Answer
1

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.

Leave a Comment