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.
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.