[wp-hackers] Programmatically add a Navigation menu and menu items
Doug Stewart
zamoose at gmail.com
Wed Mar 7 14:03:44 UTC 2012
Julien:
Answered in-thread at WPSE.
On Wed, Mar 7, 2012 at 8:44 AM, Julien Chaumond <chaumond at gmail.com> wrote:
> 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
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers
--
-Doug
More information about the wp-hackers
mailing list