WordPress loop through Menus

Since the release of WordPress 3.0 it’s possible to create custom menus.

Theme developers can enable this menu by adding the following code to ‘functions.php’:

<?php
	add_action( 'after_setup_theme', 'theme_setup' );
 
	function theme_setup() {
		register_nav_menus( array(
			'primary' => __( 'Primary Navigation', 'theme-identifier' ),
		) );
	}
?>

After this the menus will appear in ‘Appearance’ and your ready to create some custom menus the way you like.
Implementing the menu in your theme is as easy as adding this line of code:

<?php wp_nav_menu(); ?>

This will output the menu in an unsorted list (<li>’s). Of course it’s possible to style these menus by providing an arguments array, but I rather retrieve all menus in an ordered array without directly displaying them on the page.

The solution I came up with is really simple (strange it isn’t really documented on codex):

<?php
	$menus = wp_get_nav_menus();
	$menu_items = wp_get_nav_menu_items($menus[0]);
 
	foreach ($menu_items as $menu_item):
		echo "<div>";
		echo " <a href='$menu_item->url'>$menu_item->title</a>";
		echo "</div>";
	endforeach;
?>