How do I get second level menu in WordPress?

I’m over 2 hours trying many functions (wp_list_pages, get_pages, wp_nav_menu) and several functions but can’t resolve this thing out.

I have created pages that are THREE level deep:

Read More
PAGE level1
    SUBPAGE level2
        SUBPAGE level3 

and I need to display a separate menu for each of them like:

MENU1 (all top-level pages)
MENU2 (all sub-pages of CURRENT top level page)
MENU3 (all sub pages of current item from MENU2)

it should not be that complicated for a CMS like WordPress but I think I’m over-complicating possible solutions.
Do you have some suggestions on possible ways to achieve that?

Thanks.

Related posts

Leave a Reply

2 comments

  1. First of all you have to define accordance between menu items and pages. I can’t define this accordance from your question. What if you have two level2 subpages and two menu2 items? Which menu item belongs to which subpage?

    Then the process is trivial. You can get all menu items

    $menu_items = wp_get_nav_menu_items($cur_menu, array());
    

    And check menu_item_parent field to found parent items

    foreach ($menu_items as $item) {
        if ($item->menu_item_parent === $parent_id) {
            //this is child of $parent_id
        }
    }
    
  2. If you are using the the WordPress Function register_nav_menus() , it should be fairly simple.

    In your functions.php file you’ll need to register 3 separate menu’s, something like this:

    <?php
    add_action( 'init', 'register_my_menus' );
    function register_my_menus() {
      register_nav_menus(
        array( 'first' => 'first', 'second' => 'second', 'third' => 'third', )
        );
      }
    ?>
    

    With the menu’s now registered you just need to place them where they go in your theme files like so:

    The First Menu (maybe in the header.php file)

    <div id="menu">
      <?php wp_nav_menu( array( 'theme_location' => 'first' ) ); ?>
    </div>
    

    The Second Menu (maybe in the sidebar.php file)

    <div id="menu">
      <?php wp_nav_menu( array( 'theme_location' => 'second' ) ); ?>
    </div>
    

    The Third Menu (maybe in the footer.php file)

    <div id="menu">
      <?php wp_nav_menu( array( 'theme_location' => 'third' ) ); ?>
    </div>
    

    The final step is to go to Appearance>Menu’s and create the 3 menu’s, name them and choose the pages that will go with them from within the Admin Menu Settings.