Posted on Leave a comment

Using Custom Menus in WordPress Themes

Wordpress Logo

If you are creating WordPress themes from scratch and only won’t to include basic features at first enabling custom menus is a good thing to start with. Out of the box new WordPress themes do not support specifying and displaying custom menus, which you might have seen and used through the admin interface before:

In order to enable your themes to handle and display custom menus correctly only a few steps are required.

The Steps to Success

The first thing you need to do is to create functions.php (if you not already have) and add the following function:

function custom_register_nav_menu() {
    register_nav_menu('primary', __('Primary Menu', 'your_theme'));

add_action('init', 'custom_register_nav_menu');

Second, you must specify the location where your shiny new custom menu should be displayed in your theme. Therefore, locate the proper location and insert the following code:

<div id="navcontainer">
  <ul id="navlist">
    $menu_items = wp_get_nav_menu_items('Default');

    foreach ((array) $menu_items as $menu_item) {
      $title = $menu_item->title;
      $url = $menu_item->url;
      echo '<li><a href="' . $url . '">' . $title . '</a></li>';

In case the loop is too much code for you and you want to simply style the outcome produced by WordPress’ core use the following code:

wp_nav_menu(array( 'theme_location' => 'Primary Menu'));

That’s all there is to it, easy right?