Dynamically add items to a wp_nav_menu() list

WordPress’s wp_nav_menu() fetches a custom menu, as built using the Menus GUI, for display in a theme. I had a project where I needed to add some items to this menu dynamically – the links would be different for each user, and wouldn’t appear for logged-out users, so they couldn’t really be added using the GUI. After a bit of futzing, I was able to insert my menu items, tricking WP into thinking that they were native.

Details: For logged-in users, I needed to add three subnav items underneath the top-level ‘Activity’ item, if it was present. So at the beginning of the function, you’ll see that I’m doing some BuddyPress-specific stuff, to find the Activity menu. If you need to use a menu_item_parent like I did, you’ll have to supply your own method for finding it (or just hardcode it). The heavy lifting is done in the second foreach loop, where I build stdClass objects just robust enough that WordPress will interpret them as true nav menu items.

The Dynamically add items to a wp_nav_menu() list by Boone Gorges, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.

4 thoughts on “Dynamically add items to a wp_nav_menu() list

  1. cgrymala

    It should be noted, though, that if the menu is completely empty to start with, this won’t work. As of WP 3.5, the wp_get_nav_menu_items filter (and all of the actions and filters related to nav menus) only fires if there is at least one item in a menu. If the menu exists, but is completely empty, WP skips over it entirely.

    I ran into this issue when trying to get Ron Rennick’s Networkwide Menu plugin working in 3.5; I ended up having to hook into an early action, retrieve the menu, check to see if it had any items and, if it didn’t, add a dummy item to get WordPress to actually execute the necessary actions and filters.

  2. Molot

    thank you, Boone, exactly what I needed! Could you please explain the idea behind the code, since at the moment it is working weird a bit?

    If idea of the code is that it should stay inside functions.php (or any other place), then issue is that every time you will press “save menu” in Appearance -> Menus it will be adding + 3 items from the code.

    If idea of the code is that it should be run once and removed, then issue is that after you will press “save menu” in Appearance -> Menus and remove the code, 3 working items will be removed, but 3 “pending” will be kept – these 3 “pending” items have no links and respect no rules re logged in, etc.

    cgrymala, this happens to ‘wp_nav_menu_items’, but ‘wp_get_nav_menu_items’ runs fine even if menu is empty – at least from my experience with the WP 3.5.

    modemlooper, is your plugin still working, cannot find it in the repository?

    thanks!

Leave a Reply