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.

Published by

Swapnil Patil

I'm Swapnil. Nice to meet you 👋 I am a Community Manager for a fantastic #OpenSource project Devtron. I am passionate about sharing experiences on building architectures with best practices and helping strengthen the makers of tomorrow. I am keen on having discussions around DevOps, GitOps, web accessibility, User Experience & Open Source 🤘.

One thought on “Call a navigation menu using a shortcode”

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.