Unique native function to get the sub menu part in wp_nav_menu
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.
// Usage: $args = array( 'menu' => 'Menu Name', 'submenu' => 'About Us', ); wp_nav_menu( $args );
Paste this in function.php
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; }
Leave a Reply