Rendering The WordPress Menu With php


If you are a WordPress developer the day will come when you have had enough of wp_nav_menu. Although it comes with many configuration options, unusual menus that don't follow the ul/li structure are hard, if not impossible, to draw with it. 

Below is a really simple way to traverse a WordPress menu. The code below spits out the internals of each menu item. You can output whatever html you like inside the loops.

$menu = wp_get_nav_menu_object('2'); //menu parameter as in wp_nav_menu
$menu_items = wp_get_nav_menu_items( $menu->term_id, array( 'update_post_term_cache' => false ) );

ShowMenuItems($menu_items, 0);

function ShowMenuItems($menu_items, $menu_item_parent)
  foreach ($menu_items as $menu) {

    if($menu->menu_item_parent == $menu_item_parent)  {
      $title = $menu->title;
      $url = $menu->url;

      var_dump(get_object_vars($menu));//shows you the variables you have access to

//replace the above two lines with echo statements to output HTML ShowMenuItems($menu_items, $menu->ID); //recursion } } }
This code outputs the internals of each menu item object in a logical sequence. The order of items is as per the tree structure of the menu. It's really easy to grab the menu item and output html that suits your desired situation.