[wp-hackers] Programmatically add a Navigation menu and menu items

Julien Chaumond chaumond at gmail.com
Wed Mar 7 13:44:16 UTC 2012


Hi,

I need to, through API functions, define a new Navigation menu (
http://codex.wordpress.org/Navigation_Menus), select it in the current
theme, then insert a few Pages as menu items. This is to be done for
instance on a theme activation.

First of all, I've been unable to find much documentation about that: have
I overlooked something obvious?

Through a (moderately painful) process of reverse engineering the database
inserts and updates after manually setting up the aforementioned Navigation
menu and items, I've pieced together the following steps, where
'footer-nav' is the slug ID of the Navigation menu I'm creating:

if (!term_exists('footer-nav', 'nav_menu')) {

    $menu = wp_insert_term('Footer nav', 'nav_menu', array('slug' =>
'footer-nav'));

    // Select this menu in the current theme
    update_option('theme_mods_'.get_current_theme(),
array("nav_menu_locations" => array("primary" => $menu['term_id'])));

    // Insert new page
    $page = wp_insert_post(array('post_title' => 'Blog',
                                 'post_content' => '',
                                 'post_status' => 'publish',
                                 'post_type' => 'page'));

    // Insert new nav_menu_item
    $nav_item = wp_insert_post(array('post_title' => 'News',
                                     'post_content' => '',
                                     'post_status' => 'publish',
                                     'post_type' => 'nav_menu_item'));


    add_post_meta($nav_item, '_menu_item_type', 'post_type');
    add_post_meta($nav_item, '_menu_item_menu_item_parent', '0');
    add_post_meta($nav_item, '_menu_item_object_id', $page);
    add_post_meta($nav_item, '_menu_item_object', 'page');
    add_post_meta($nav_item, '_menu_item_target', '');
    add_post_meta($nav_item, '_menu_item_classes', 'a:1:{i:0;s:0:"";}');
    add_post_meta($nav_item, '_menu_item_xfn', '');
    add_post_meta($nav_item, '_menu_item_url', '');

    wp_set_object_terms($nav_item, 'footer-nav', 'nav_menu');

}


This seems to work, but I would love to check with you guys whether this is
a robust or elegant way of doing it, or if I'm missing something totally
obvious that would do all this in one line of code.

For the sake of legibility and content duplication, I've also posted this
code to wordpress.stackexchange:
http://wordpress.stackexchange.com/questions/44736/programmatically-add-a-navigation-menu-and-menu-items

Thanks!

Julien


More information about the wp-hackers mailing list