Include a custom WordPress menu in a page template

There may be some cases where you want to add a secondary menu to your WordPress theme, for example for a Members only section. This tutorial will run you through how to set it up and add it into a page template.

Create a custom menu

To create a custom menu follow these steps:

  • In the WordPress admin area go to 'Appearance' > 'Menus'
  • Click 'create a new menu' at the top of the page
  • You can now either use existing pages from your site using the left panel, or use 'Links' if you want to use custom or external URLs to build up your menu
  • Once finished click save

Adding a custom menu to a page template

Next we want to use the menu inside a custom page template.  To achieve this, we need to create a new theme location by adding the following snippet of code into your functions.php file:

function register_menus()
{
    register_nav_menus(
        array('member_navigation' => __( 'Members Navigation' ))
    );
}
add_action( 'init', 'register_menus' );

If you now go back to your menu via 'Appearance' > 'Menus' and click on the 'Manage Locations' tab you'll see there is now a second theme location available.

Select your new menu and tick the new theme location. If you don't do this your new location will default back to the primary menu.

To use this new menu, you now need to add the following code to the template where you want it to appear:

wp_nav_menu(array(
    'theme_location' => 'member_navigation',
    'container' => false,
    'menu_class' => 'nav'
));

You can read more about the other arguments that can be passed into the wp_nav_menu function in the WordPress Codex.

Restrict the menu to members-only

If you want to restrict the menu so that only visitors who are logged in can view it, simply wrap the following code around the wp_nav_menu function:

if (is_user_logged_in())
{
    // Logged in only code...
}
Sign Up
comments powered by Disqus
Sign Up

Popular Tags

350x250

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.