How to assign a WP 3.0 custom nav menu to a theme’s navigation menu location via script?

I’m using this script inside a plugin to create a new custom menu on the fly and assign a page to it…

$menu_id = wp_create_nav_menu( 'header-menu' );
$menu = array( 'menu-item-type' => 'custom', 'menu-item-url' => get_home_url('/'),'menu-item-title' => 'Home', 'menu-item-status' => 'publish' );
wp_update_nav_menu_item( $menu_id, 0, $menu );

And this works great. However, what I’m stuck on is how to hook this menu up to one of my theme’s “Menu Locations”. Since I’m registering a nav location called “header-menu” in my theme’s functions.php, I thought that the code above, calling wp_create_nav_menu( ‘header-menu’ ) would hook my custom menu to the location defined in my theme as “header-menu”, but its not.

Read More

For example, my theme registers two menu locations…

register_nav_menus(
  array('header-menu' => __( 'My Header Menu' ), 
 'footer-menu' => __( 'Footer Menu' ))
);

How can I hook the “Header Menu” I created with wp_create_nav_menu( ‘Header Menu’ ) to the “My Header Menu” location that i’ve registered in my theme? I’m sure the answer is somewhere in nav-menu.php, but I can’t find it.

ie, I can do this manually from the WordPress “Appearance > Menus” Manager and under “Theme Locations > Main Navigation Menu” I select “Header Menu” and click “Save”. I’m trying to do this in script.

Related posts

Leave a Reply

1 comment

  1. If you’ve already found an answer to this that works well for you, I encourage you to post it here for others to see. If not, the way I would go about it would be to use a custom filter or an action.

    Where the menu is output in the theme, either use apply_filters or do_action to trigger the override you want, and in your plugin, hook into that action/filter to output the override. This is a more non-destructive way of accomplishing the same task, as you then don’t overwrite a menu association.