I’ll try to be brief….
I have a theme that only supports one navigation menu. At this point I’d like to add 2 or 3 more menus. I have successfully registered my menus in functions.php with register_nav_menus and I am able to switch the header.php code manually between my different menus.
My problem…
Since my theme uses a single header (header.php) I can’t assign my pages or posts the navigation menu I want without changing all the other pages navigation menus.
Can anyone help me out on this?
Thanks in advance.
Greg
First off, some things you should know about nav menus:
nav_menu
.In short: menus are just like nearly every other piece of content in WordPress, they just have a custom UI.
With that out of the way, the task is fairly simple: put a custom meta box on your edit screen that shows options to choose nav menus. On the front end, switch the nav menu out to whatever you set in the admin area. The only thing to worry about is what the
theme_location
value is for your theme’s call towp_nav_menu
. Where do you want to switch the menu out?This is example will use Twenty Twelve, which uses the theme location
primary
.A call to wrap everything up in:
Now let’s add our meta box. Since this is covered in detail a great many places, I’ll give the cliff notes explanation: hook into
add_meta_boxes
, calladd_meta_box
. In the meta box callback function, output a nonce and your field(s).To save the values, hook into
save_post
, check to make sure we are where we want to be (no autosave, nonce validates) and that the current user can edit the post, save (or delete) the value with(update|delete)_post_meta
.Notice the helper method to retrieve the nav menus. Not much, just a convenient helper that runs the result through a filter.
Finally, we just need to switch out the menu. To do that, hook into
wp_nav_menu_args
and, if we’re on a singular page and have the correct theme location, switch out the menu as appropriate. Some extra filters are included to make this a bit more extensible.All of the above as a plugin.