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;
?>
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • YahooMyWeb

5 thoughts on “WordPress loop through Menus

  1. Hey Patrick,

    Nice and simple solution.

    The reason this is not in the codex, is that the codex mentions the use of a custom walker. With a custom walker you can achieve the same solution, but I think thats how the WordPress devs created

    Greetz,
    Marco

  2. Thank you so much! I am doing a client site and needed something like this!

    You have no idea how happy I am haha.

    Cheers,
    Tyler

  3. How to print submenu through loop. The below code show all menu in li, submenu does not come in ul.
    Thank X in advance
    <?php
    $menus = wp_get_nav_menus();
    $menu_items = wp_get_nav_menu_items($menus[0]);

    foreach ($menu_items as $menu_item):
    echo "”;
    echo ” url’>$menu_item->title“;
    echo “”;
    endforeach;
    ?>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">