automatically placing custom post types singles into submenu of main nav menu

Walker_Nav_Menu isn’t what you would use for this.

Instead, use the wp_get_nav_menu_items filter. Before we start, you need some way of allowing the code to identify which is the menu item/page that you wish to be the parent of the list of posts. You can do this with a CSS class – give the parent menu item a CSS class in admin panel, let’s call it ‘doctors-parent-item’.

add_filter( 'wp_get_nav_menu_items', 'my_theme_doctors_menu_filter', 10, 3 );

function my_theme_doctors_menu_filter( $items, $menu, $args ) {
  $child_items = array(); // here, we will add all items for the single posts
  $menu_order = count($items); // this is required, to make sure it doesn't push out other menu items
  $parent_item_id = 0; // we will use this variable to identify the parent menu item

  //First, we loop through all menu items to find the one we want to be the parent of the sub-menu with all the posts.
  foreach ( $items as $item ) {
    if ( in_array('doctors-parent-item', $item->classes) ){
        $parent_item_id = $item->ID;
    }
  }

  if($parent_item_id > 0){

      foreach ( get_posts( 'post_type=rt_doctors&numberposts=-1' ) as $post ) {
        $post->menu_item_parent = $parent_item_id;
        $post->post_type="nav_menu_item";
        $post->object="custom";
        $post->type="custom";
        $post->menu_order = ++$menu_order;
        $post->title = $post->post_title;
        $post->url = get_permalink( $post->ID );
        array_push($child_items, $post);
      }

  }

  return array_merge( $items, $child_items );
}

Your menu will now dispaly all rt_doctors‘s in a sub menu underneath the menu item that you gave the CSS class ‘doctors-parent-item`

Leave a Comment