functions.php
// filter menu to submenu
add_filter( 'wp_nav_menu_objects', 'submenu_limit', 10, 2 );
function submenu_limit( $items, $args ) {
if ( empty( $args->page_parent ) ) {
return $items;
}
$subitems = array();
foreach ($items as $key => $item) {
if($item->post_parent == $args->page_parent){
$subitems[] = $item;
}
}
foreach ($subitems as $key => $subitem) {
submenu_get_children($items, $subitems, $subitem);
}
return $subitems;
}
function submenu_get_children($items, &$subitems, $subitem){
foreach ($items as $key => $item) {
if($subitem->ID == $item->menu_item_parent){
$subitems[] = $item;
submenu_get_children($items, $subitems, $item);
}
}
}
Usage in template
$parents = get_post_ancestors( $post->ID );
$parent_id = ($parents) ? $parents[count($parents)-1]: $post->ID;
$args = array(
'post_parent' => $parent_id,
);
$children = get_children( $args );
// optional, check if page has children
if($children){
wp_nav_menu([
'menu' => 'menu-1',
'theme_location' => 'menu-1',
'container' => '',
'container_id' => '',
'container_class' => '',
'menu_id' => false,
'menu_class' => 'navbar-nav',
'depth' => 3,
'page_parent' => $parent_id
]);
}