You would need to use a custom class extending Walker_Nav_Menu
, which is the default walker for wp_nav_menu()
.
Implementation would be as such:
$args = [ 'menu_id' => 'main_menu', 'walker' => new SE287172_Walker_Nav_Menu() );
wp_nav_menu( $args )
You would also want to add a custom class to the menu item. For this example, we’ll go with vinayak-custom-class
, as you’ll see in the walker’s code below.
You would need to define your Walker, and override the start_el()
method. This would allow you to add additional HTML Markup depending on a number of things. You have the Menu Item object at hand, so you could base the custom submenu on a class, the title, the ID, etc.
I’d recommend a class, as hard-coding to a title may screw you over if the “SPORTS” menu item ever changes to be “Our Sports” or something similar and your sub-menu disappears.
You would place this in your functions.php
file or ideally, another file in a /includes/my-nav-menu-walker.php
file (or similar) where you keep your code organized.
class SE287172_Walker_Nav_Menu extends Walker_Nav_Menu {
public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
// Let the main class do it's thing first. Then shove your submenu in.
parent::start_el( $output, $item, $depth, $args, $id );
// Now do your class check
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
if ( in_array( 'vinayak-custom-class', $classes ) {
// Do your Submenu HTML Output
$output .= 'My Sports Sub-menu goes here';
}
}
}
At this point, you can then do a get_posts()
call within the class check to grab your pages in your Sports category, and loop through them, creating your <li>
structure.