Merging WordPress 3.1 menus

As I am working on a new site for our local photography club I stumbled upon a small problem. I needed to add menu items to the main menu but only for registered users. WordPress doesn’t have the option, yet, to assign roles to menu items.
I know this “problem” can be solved by creating two, almost identical, menus in WordPress and show the members menu when a member is logged. In that situation you would need to maintain two menus in WordPress, if you add an item t o the general menu, you also need to remember to add it to the members menu. With two menus that’s not that big of a deal, but what if you want to have menu items for different roles or even categories.

The snippet

I found the solution by hooking in to the wp_nav_menu_objects filter.

add_filter('wp_nav_menu_objects', 'members_menu', 10, 2);
function members_menu($sorted_menu_items, $args)
    if ($args->theme_location == 'Primary' && is_user_logged_in()){
        $header_members_items = wp_get_nav_menu_items('Header_members');
        _wp_menu_item_classes_by_context( $header_members_items );
        foreach ($header_members_items as $item) {
    return $sorted_menu_items;

Some explanation about the code and some background information

I use multiple menus on my site and I only need to add the member items to the menu in my header. This menu is registered as Primary in my theme.
I created a menu in WordPress called Header_members which will hold only the menu items that need to be displayed if somebody is logged in.

$args->theme_location == 'Primary'

This checks to see which wp_nav_menu is being used as if you have multiple menus you don’t want to add the member items to every menu displayed.

The function call on line 6 is needed as the menu items of the Header_members menu don’t have their classes assigned. The filter wp_nav_menu_objects is being called after the the classes have been assigned to the current menu being displayed.

The example code is for registered members to a blog but the possibilities are almost endless of course. You could create menu items for certain categories and show them only when a post/page has those categories.

I hope this WordPress code snippet is useful for some people. Let me know if you implemented this in your own blog and with what purpose.

This article is filed under the categories Development » WordPress » Code Snippet and has no tags associated with it.