This was still on my mind so I revisited it and put together this solution, that does not rely on context that much:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | add_filter( 'wp_nav_menu_objects', 'submenu_limit', 10, 2 ); function submenu_limit( $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; } |
Usage
1 2 3 4 5 6 | $args = array( 'theme_location' => 'slug-of-the-menu', // the one used on register_nav_menus 'submenu' => 'About Us', // could be used __() for translations ); wp_nav_menu( $args ); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.