Add Nav Menu In Content Area Using Shortcode

This tutorial includes the PHP code which creates a shortcode for any nav menu in any theme.

There’s 2 examples includes in this post:

  1. The 1st snippet works in the Twenty Twelve default theme for WordPress. It will also work in any other theme as long as you change the menu class to match what your theme uses.
  2. The 2nd snippet works in Genesis and will also work in any other theme if you also change the menu class.

Here’s what the shortcode outputs in Genesis when added in between text in your WordPress editor.

genesis menu

Simply change the menu class to match what your theme uses otherwise you menu may display vertically like a unordered list.

This tutorial answers this forum question:

Any idea how I can insert a menu into the body of a page? I do not want it in a side bar or in standard menu locations.


Comments

4 responses to “Add Nav Menu In Content Area Using Shortcode”

  1. Ivan Podnar Avatar
    Ivan Podnar

    Hi, if I create new menu, example: ThirdMenu via Menus>Edit Menus> create a new menu, can I
    – still create shortcode
    – if yes, what script to use,
    – if no, using your post Adding Additional Nav Menu’s in Genesis
    https://wpsites.net/web-design/adding-additional-nav-menus-in-genesis/
    I have an issue with genesis_entry_content hook position where new menu is showing on every page

    ( using News Pro theme) ,

    1. Brad Dalton Avatar
      Brad Dalton

      Did you republish members only content on the StudioPress forums?

  2. Quick FYI: You can call wp_nav_menu with echo=false parameter so as not to need the ob_start/ob_get_contents/ob_end_clean calls.

    The function would become one line:
    wp_nav_menu( array( ‘menu’ => ‘Primary’, ‘menu_class’ => ‘genesis-nav-menu’, ‘echo’ => false ) );

    1. Brad Dalton Avatar
      Brad Dalton

      Yep, saw that and had tested it locally but it (dare i say it) doesn’t work properly on all themes.

      There’s many ways you could code this but i wanted something that also works on non Genesis themes as well like Twenty Twelve.

      Plus i wanted a solution which is unique that i worked out myself.

      You could also add the checks which the parent theme includes like this:

      [code]
      //* Do nothing if menu not supported
      if ( ! genesis_nav_menu_supported( ‘primary’ ) )
      return;

      $class = ‘menu genesis-nav-menu menu-primary’;
      if ( genesis_superfish_enabled() ) {
      $class .= ‘ js-superfish’;
      }

      genesis_nav_menu( array(
      ‘theme_location’ => ‘primary’,
      ‘menu_class’ => $class,
      ) );
      [/code]

      Also the output buffering is used when filtering the nav menu to add a widget area or search box.

      You could also code the add_shortcode function differently.

      Thanks Damien.

Leave a Reply

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.