Greetings! I'm Aneesh Sreedharan, CEO of 2Hats Logic Solutions. At 2Hats Logic Solutions, we are dedicated to providing technical expertise and resolving your concerns in the world of technology. Our blog page serves as a resource where we share insights and experiences, offering valuable perspectives on your queries.
We were working on our WordPress project and we had found a problem that when using wp_nav_menu(), there is no native function to get submenu part in another element. eg: sidebar. We found a solution which can be used to avoid this problem. Please find below code.
Just add the ‘submenu’ in the arguments for the wp_nav_menu(). Then the label name of the top-level menu that has the submenu that you want to list.
1 2 3 4 5 6 7 | // Usage: $args = array( 'menu' => 'Menu Name', 'submenu' => 'About Us', ); wp_nav_menu( $args ); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | add_filter( 'wp_nav_menu_objects', 'submenu_limit', 10, 2 ); function submenu_limit( $items, $args ) { if ( empty($args->submenu) ) return $items; $parent_id = array_pop( wp_filter_object_list( $items, array( 'title' => $args->submenu ), 'and', 'ID' ) ); $children = submenu_get_children_ids( $parent_id, $items ); foreach ( $items as $key => $item ) { if ( ! in_array( $item->ID, $children ) ) unset($items[$key]); } return $items; } |