Displaying current page's title in addition to its immediate children in a menu


(Isaiaiah) #1

Hey everyone,

I have the following code which outputs the immediate children of the page the user is currently viewing.

add_filter( 'wp_nav_menu_objects', 'submenu_branch', 10, 2 );
 
function submenu_branch( $items, $args ) {
 
  if ( empty( $args->submenu ) ) {
    return $items;
  }
 
  $ids = wp_filter_object_list( $items, array( 'title' => $args->submenu ), 'and', 'ID' );

  $parent_id = array_pop( $ids );
  
  $children = submenu_get_children_ids( $parent_id, $items );

  foreach ( $items as $key => $item ) {
    if (!in_array( $item->ID, $children )) {
      unset( $items[$key] );
    }
  }

  return $items;
}
 
function submenu_get_children_ids( $id, $items ) {
 
  $ids = wp_filter_object_list( $items, array( 'menu_item_parent' => $id ), 'and', 'ID' );
 
  foreach ( $ids as $id ) {
    $ids = array_merge( $ids, submenu_get_children_ids( $id, $items ) );
  }
  return $ids;
}

global $post;
$post_title = $post->post_title;

$args = array(
  'menu'    => 'main-menu',
  'submenu' => $post_title
);
 
wp_nav_menu( $args );

What I’d like to do is for this code to display not only the immediate children but also the title/link of the page the user is currently viewing (the parent of the children being currently displayed). Is that possible to achieve? Any tips would be greatly appreciated and thanks in advance.