Bright White Space

WordPress parent and child pages for sidebar navigation

A useful snippet of code for WordPress websites which need to display a sidebar for the current page and it’s child pages. This code retrieves the current top level parent page and displays all child pages underneath. The two functions sit in the functions.php file within your theme and are called from within the page where you want the menu to appear:



$topLevelId = getTopLevelId();
$sideBarNav = getSideNav($topLevelId,get_the_ID());

echo $sideBarNav();




function getTopLevelId(){
    $ancestors = get_ancestors( get_the_ID(), 'page' );

    $topLevelId = end($ancestors);
    if(!$topLevelId):
        $topLevelId = get_the_ID();
    endif;

    return $topLevelId;
}

function getSideNav($topLevelId, $currentPageId){

    $args = array(
        'post_type'      => 'page',
        'posts_per_page' => -1,
        'post_parent'    => $topLevelId,
        'order'          => 'ASC',
        'orderby'        => 'menu_order'
    );

    $parent = new WP_Query( $args );

    $html = '';

    if ( $parent->have_posts() ) {

        $html .= '<ul>';

        while ( $parent->have_posts() ) {
            $parent->the_post();
            $html .= get_the_ID() == $currentPageId ? '<li class="current-menu-item">' : '<li>';
            $html .= '<a href="'.get_permalink().'" title="'.get_the_title().'">'.get_the_title().'</a>';
            $html .= getSideNav(get_the_ID(),$currentPageId);
            $html .= '</li>';
        }

        $html .= '</ul>';
    }
    wp_reset_query();

    return $html;
}

 

Exit mobile version