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 want to create one menu for all users and then hide / remove items from the menu if they don't have access to the page the link leads to. This to me seem like an SOP. I really don't understand how this is not a core functionality. I can't possibly be the first one to want or think of such an idea. anyway

here is what i have so far I'm just not sure how or where to get the post id from

add_filter( 'wp_nav_menu_items', 'rm_menu_items', 10, 2 );

function rm_menu_items( $items, $args ) {
    foreach($items as $key=>$item){

        if (!current_user_can('read', $post_id)){
            unset($items[$key]);
        }
    }

   return $items;
}
share|improve this question
    
interesting got down vote .... –  mcgrailm Aug 13 '13 at 5:07
add comment

2 Answers

If you use the 'wp_nav_menu_objects' filter, you get a list of menu items before the Walker processes them. Each menu item is a WP_Post object with some menu specific properties added in. The ID property is the post ID.

add_filter( 'wp_nav_menu_objects', 'rm_menu_items', 10, 2 );

function rm_menu_items( $menu_items, $args ) {

    $allowed_menu_items = array();

    foreach ( $menu_items as $menu_item ) {

        if ( current_user_can( 'read', $menu_item->ID ) )
            $allowed_menu_items[] = $menu_item;
    }

   return $allowed_menu_items;
}

You can see more details about menu items here

share|improve this answer
    
right on .. what i like about this approach better than a plugin where I have to check who is allowed to see it this will just works off a flag that's already set :) i'll check it to make sure it works , but I'm guessing it will work out fine :) –  mcgrailm Aug 13 '13 at 5:01
    
seems to wipe out the entire menu.. I'll look into it more tomorrow :) –  mcgrailm Aug 13 '13 at 5:14
    
i see now if they are not registered then they can't read so this I am slightly off trying to use "read" permission as the toggle –  mcgrailm Aug 13 '13 at 11:18
    
Which posts are unregistered users not allowed to read? Do they share a common characteristic? –  Charles Clarkson Aug 13 '13 at 23:20
    
they all have content permissions enabled imgur.com/WNxYweS so that only users with a specific role can see them –  mcgrailm Aug 14 '13 at 1:08
show 2 more comments

This was asked here a couple of years ago.

Display navigation menu item conditionally based on user capabilities

There are several options there that would work.

share|improve this answer
    
This lead me to a plug in that works pretty well as a backup plan –  mcgrailm Aug 13 '13 at 5:02
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.