How I convert wp_list_pages to wp_nav_menu in WordPress Theme

Some older WordPress websites I’ve developed use the WordPress function wp_list_pages() to display the websites main menu. While this function works fine, there are more flexible functions to display your website menu.

My choice is to use function wp_nav_menu() for the website menu.

In the theme, I use wp_list_pages() in my header.php file. The code looks something like this.

<div id="mainmenu">
  <ul id="dropmenu">
    <?php wp_list_pages('title_li='); ?>

The first thing I did is to try and add the new function to header.php.

<div id="mainmenu">
      $args = array(
        'theme_location'  => '',
        'menu'            => 'Primary',
        'container'       => '',
        'container_class' => '',
        'container_id'    => '',
        'menu_class'      => '',
        'menu_id'         => '',
        'echo'            => true,
        'fallback_cb'     => 'wp_page_menu',
        'before'          => '',
        'after'           => '',
        'link_before'     => '',
        'link_after'      => '',
        'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
        'depth'           => 0,
        'walker'          => ''
      wp_nav_menu(  $args  );

When I loaded the site, I received this error.
Your theme does not support navigation menus or widgets.
I need to tell WordPress that I’m now using a menu, and need to register the menu that I’m using. Here is the code that needs to be added to functions.php.

register_nav_menus( array(
  'primary' => __( 'Primary Menu', 'dcccmh' ),
) );

Once that’s been added, the site will work, but the menu still doesn’t display. This is because I need to create my menu in Appearance > Menus in the WordPress administration.
Once I’ve build my menu in WordPress, adding the pages that I want displayed in the menu, it will now display on the site.

Unfortunately, there are some more tweaks to get it to display using the CSS styling I’ve already used to display the old menu.
I viewed the source of the page and needed to duplicate my ul tag to match the old menu, so the styles are applied properly.
Since I wrapped the old menu ul tag with an id of dropmenu, I just added that to my arguments for wp_nav_menu().
Here’s is what I changed to make it work. Note the ul id for dropmenu.

'items_wrap' => '<ul id="dropmenu">%3$s</ul>',

Once my navigation list was wrapped in the dropmenu ul tag, the menu looked identical to the old menu.

This turned out to be easier than I thought it would be, and is more flexible, in that I can maintain the menu directly in the Menus section of WordPress.


by Norm Euker