Using wp_get_nav_menu_items() to list children of children pages

I’m working with a Genesis Based Theme and I’d like build a Page/ Child Page menu structure. That part I can do with the help of some code produced by Bill Erickson.

Essentially what I’m trying to do is create a menu above content on pages with child pages. Then, in the left sidebar, have navigation for children pages with children. I’ve got something setup here: sandbox.digisavvy.com

Read More

Here’s the code I’m working from.

<?php

/**
 * Section Menu
 * Displays the subpages of the current section
 *
 * @author Bill Erickson
 * @link http://www.billerickson.net/custom-secondary-menu
 */
function be_section_menu() {

    // Only run on pages
    if( !is_page() )
        return;

    // If top level page, use current ID; else use highest ancestor
    global $post;
    $section_id = empty( $post->ancestors ) ? $post->ID : end( $post->ancestors );

    // Get all the menu locations
    $locations = get_nav_menu_locations();
    // Find out which menu is in the 'primary' location
    $menu = wp_get_nav_menu_object( $locations[ 'primary' ] );
    // Grab all menu items in this menu that have a parent of the current section.
    // This grabs the subpages, assuming the current section is a top level page
    $menu_items = wp_get_nav_menu_items( $menu->term_id, array( 'post_parent' => $section_id ) );
    // If there are menu items, build the menu
    if( !empty( $menu_items ) ) {
        echo '<ul class="section-submenu">';
        $first = true;
        foreach( $menu_items as $menu_item ) {
            $classes = 'page-item';
            // This adds a class to the first item so I can style it differently
            if( $first )
                $classes .= ' first-menu-item';
            $first = false;
            // This marks the current menu item
            if( get_the_ID() == $menu_item->object_id )
                $classes .= ' current_page_item';
            echo '<li class="' . $classes . '"><a href="' . $menu_item->url . '">' . $menu_item->title . '</a></li>';
        }
        echo '</ul>';
    }

}
add_action( 'genesis_before_loop', 'be_section_menu' );

The next part that I’d like to accomplish is to create a menu system with Child Page/ Child of Child Page. That’s the part where I’m stuck. This code below is suggested as a change, but doesn’t quite do the trick. It just adds the children of children to the navigation.

global $post;
$level = count( $post->ancestors );
// Only build tertiary menu if current page is at least third level
if( 1 > $level )
    return;
$section_id = $post->ancestors[$level - 2];

Related posts

Leave a Reply

2 comments