[wp-hackers] hide specific nav items from public users (Kapil Chugh)

Ryann Micua ryannmicua at gmail.com
Sun Jul 1 13:15:34 UTC 2012


Hey Kapil here's how I used the wp_get_nav_menu_items filter.

But first some context: I have this plugin that uses a custom post type 
- "private page". I won't get into much details, but it basically 
functions like a normal wp page, only difference is that an admin 
chooses which users (non-admins) can view this page. The admin then uses 
the "custom menu widget" to add this "private pages" as menu items to 
the sidebar. Now the problem, the menu must only show items that the 
current user (non-admin) has permission to see.

add_filter('wp_get_nav_menu_items', 'filterNavMenuItems', 10, 3 );
/**
  * Filter nav menu items - show only allowed menu items to the current user
  */
function filterNavMenuItems( $items, $menu, $args ){
     if( !is_array( $items ) ){
         return $items;
     }

     $currentUserId = get_current_user_id();

     //loop through each nav menu item
     foreach( $items as $index => $item ){

         //check if current item refers to our custom post type 
"private_page"
         if( $item->object == "private_page" ){
             //get the post object ID.
             $post = get_post( $item->object_id );

             //stop and continue with next $item if $post is empty
             if( empty( $post ) ) continue;

             //make sure that current user has permission to view this page
             if( !PPP_Utils::userCanAccess( $currentUserId, $post ) ){

                 //remove this $item from $items array
                 unset( $items[$index] );

             }
         }
     }

     return $items;
}

Hope this helps someone else..

> Ryann, please share your code.
>
> Best Regards,
>
> Kapil Chugh


-- 
*Ryann Micua*
/Web Developer/
------------------------------------------------------------------------

Website: /www.pogidude.com/
Skype: /rmicua/
Mobile: /+639169273059/



More information about the wp-hackers mailing list