How to dynamically create a navigation menu
By automating site creation on WordPress, you can also automate the creation of the site tree structure, for example for a prototype.
In the example below, no pages are used. Navigation is based on custom links, starting from a 2-level navigation defined in the array.
Add this function to your plugin or function file:
<?php /* * Create programmatically navigation menu */ add_action('after_setup_theme', 'wpster_create_nav_menu'); function wpster_create_nav_menu() { $menu_name = 'Menu Principal'; $menu_exists = wp_get_nav_menu_object($menu_name); if (!$menu_exists) { $menu_id = wp_create_nav_menu($menu_name); $items = array( array( 'Accueil', ), array( 'Ventes','BMW','Mini','Voir tout', ), array( 'Carrosserie', ), array( 'Atelier','Entretien','Réparations','Équipement','Accessoires', ), array( 'Contact & Accès', ), ); foreach($items as $key=>$value): $parent = 'parent_'.$key; foreach($value as $kvalue=>$vvalue): if($kvalue==0): $$parent = wp_update_nav_menu_item($menu_id, 0, array( 'menu-item-title' => __($vvalue), 'menu-item-url' => '#', 'menu-item-status' => 'publish') ); else: $child = wp_update_nav_menu_item($menu_id, 0, array( 'menu-item-title' => __($vvalue), 'menu-item-url' => '#', 'menu-item-parent-id' => $$parent, 'menu-item-status' => 'publish') ); endif; endforeach; endforeach; } } ?>