The wp_nav_menu Shortcode for WordPress Menus

Since WordPress 3.0 we have access to the really useful wp_nav_menu shortcode functionality. We can now create our own menus without resorting to several plugins or tricks.

Another cool thing we can do with this new menu is build the sitemap. I was in need, the other day, of a plugin that would generate a sitemap page (something like an archive page). Not an XML sitemap, just a standard page from where the site’s visitors could navigate more easily. The best solution appeared to be a WordPress menu shortcode.

Since I couldn’t find something like this, I realized that I could use the wp_nav_menu function and built a shortcode to insert it into my page.

The wp_nav_menu Shortcode

To install the shortcode just place this code inside the functions.php file of your theme.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Function that will return our WordPress menu
function list_menu($atts, $content = null) { extract(shortcode_atts(array( 'menu' => '', 'container' => 'div', 'container_class' => '', 'container_id' => '', 'menu_class' => 'menu', 'menu_id' => '', 'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'depth' => 0, 'walker' => '', 'theme_location' => ''), $atts));
 
  return wp_nav_menu( array( 'menu' => $menu, 'container' => $container, 'container_class' => $container_class, 'container_id' => $container_id, 'menu_class' => $menu_class, 'menu_id' => $menu_id, 'echo' => false, 'fallback_cb' => $fallback_cb, 'before' => $before, 'after' => $after, 'link_before' => $link_before, 'link_after' => $link_after, 'depth' => $depth, 'walker' => $walker, 'theme_location' => $theme_location));
}
//Create the shortcode
add_shortcode("listmenu", "list_menu");

To use the shortcode just place [listmenu menu=Sitemap] into your post and that’s it (replace Sitemap with the id, slug, or name of the menu you want to list).

You can also use all the variables that come with the new wp_nav_menu function, like menu_class, or container, so you can customize your menu really easily. Just separate the attributes by space like so:
[listmenu menu=Sitemap menu_class=sitemap_menu]

Conclusions

This is really useful for client sites, where you want to make it easy to edit and modify the site without breaking the HTML. We could have just manually created the sitemap, but this is a lot nicer. Another way you could use this shortcode would be to create sub-menus on certain pages only.

If you find use for this shortcode in an interesting way don’t hesitate to share it in the comments.

Subscribe to get early access

to new plugins, discounts and brief updates about what’s new with Cozmoslabs!

Source: https://www.cozmoslabs.com/1170-wp_nav_menu-shortcode/


You might also like this video