Sillybean
Call a navigation menu using a shortcode
Today I came across a weird situation: I needed to place a navigation menu in the content of a page. A shortcode was the obvious solution, but there doesn’t appear to be one built in for menus. I created this one very quickly:
function print_menu_shortcode($atts, $content = null) {
extract(shortcode_atts(array( 'name' => null, ), $atts));
return wp_nav_menu( array( 'menu' => $name, 'echo' => false ) );
}
add_shortcode('menu', 'print_menu_shortcode');
Place this in functions.php, then use [menu name="main-menu"] to call the menu in your content (replacing "main-menu" with your menu’s slug, of course).
You could adapt this to accept any of the other arguments available for wp_nav_menu(), but this served my purposes.
Posted on July 13, 2010 at 11:34 am in WordPress · 11 comments
Sharing this post? The short URL is: http://sillybean.net/?p=5594




Thanks for the post. I wrote it like this:
function my-shortcode-name() {
return wp_nav_menu( array( ‘theme_location’ => ‘mymenu-name’,'depth’ => ’2′,’menu_class’ => ‘my-class-name’, ‘echo’ => false ) );
;}add_shortcode(‘my-shortcode-name’,'my-shortcode-name’);
One problem tough. When I put the shortcode in a custom post type field the class “current_page_item” wont show up as it should. Any solution for this?
I tested “wp_reset_query();”:
function my-shortcode-name() {
wp_reset_query();
return wp_nav_menu( array( ‘theme_location’ => ‘mymenu-name’,'depth’ => ’2′,’menu_class’ => ‘my-class-name’, ‘echo’ => false ) );
;}add_shortcode(‘my-shortcode-name’,'my-shortcode-name’);
It works on pages but mess up the site on posts.
Any solution?
BR.
Hakan
Thnak you!! This is brilliant! I am not a coder but this was exactly what I needed. I saw some popup somewhere to donate but don’t now. I will throw in a few bucks for this.
Thanks for this post, it helped me a lot !
That’s great! I searched now for while to solve that problem because I did too many widgets with widget logic and now this works out of the box – copy&paste and done – thanks a lot!
Great!
Thank You
Thank you!
I added this to our customer knowledgebase as well:
http://www.anysitesupport.com/how-do-i-add-a-wordpress-menu-to-the-content-of-my-page/
And linked back to here for reference. This really saved one of our customers – thanks again!
Awesome. Used this in conjunction with a SlideDeck for front page nav. Stellar.
Thanks!
Matt, LOVE SLIDEDECK! I just checked it out from your post and it is so great! I am definitely purchasing it Thanks for that tip.
Now need a slight edit – any thoughts?
Need the ability to display just the sub pages from the page it displays on?
Hmm, tricky. If you can use a plain old page list instead of the menu, I can do that! Here’s the code for a theme file, a functions.php filter, or a shortcode.
I was about to write this same code, then I thought I bet someone else has had this same exact issue so I searched, and sure enough… This worked great, thanks!