Show menu based on parent & ancestor

Trying to show a wp menu based on parent. Works great on parent / child pages, but on grandchildren pages its failing. How should i restructure the menu selector to include the sub nav menu based on the main parent?

<?php
if ( wp_get_nav_menu_object( $post->post_title ) ) {
wp_nav_menu( array( 
'menu' => $post->post_title,
'menu_class' => 'subnav',
'container' => ''
) );
} else {

   if ( wp_get_nav_menu_object( get_the_title( $post->post_parent ) ) ) {
wp_nav_menu( array( 
'menu' => get_the_title( $post->post_parent ),
'menu_class' => 'subnav',
'container' => ''
) );
}
 }

?>

Related posts

Leave a Reply

1 comment

  1. Work around.

    if (is_page( 'pagename' ) || in_array("5", $post->ancestors)) {
    wp_nav_menu( array( 'container_class' => 'subnav', 'menu' => 'visit' ));
    

    }

    5 being the ID of the page in question.

    So while this is a bit more work, needing and if / if:else statement for each page, it will scale to allow as many child / grandchild pages as needed