WordPress has the wp_nav_menu() function which is quite powerful and can take a number of parameters that will allow to control the classes and IDs of html tags, the name of the menu and many more.
In this article, we will check modify submenu class name using the walker in wp_nav_menu. Wp_nav_menu is a WordPress function which is useful to display menus to the frontend.
This function provides many parameters using that you can modify display part of the menu. But it is not enough for a satisfying requirement. Sometimes we want to change the class of inner html section which is not possible using provided parameters so WordPress provided another option is known as Walker Class. You can extend Walker_Nav_Menu class and do modification you want to.
Also Read: To change File/Image Upload Path in WordPress
The walker I’d like to point out here is the wp_nav_menu() function, which looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | wp_nav_menu( array( 'menu' => 'Main Menu', 'walker' => new CD_Walker_Nav_Menu() ) ); // Change Sub-Menu class name class CD_Walker_Nav_Menu extends Walker_Nav_Menu { function start_lvl( &$output, $depth = 0, $arg = Array() ) { $indent = str_repeat( "\t", $depth ); $output .= "\n$indent<div class=\"menu-container\">\n<a class=\"mp-back\" href=\"#\">" . __('back', 'cd') . "</a><ul>"; } function end_lvl( &$output, $depth = 0, $arg = Array() ) { $indent = str_repeat( "\t", $depth ); $output .= "\n$indent</ul></div>"; } } |
Explanation:
Here we have extended the Walker_Nav_Menu class with the new class and in that want to change submenu class name so used two functions start_lvl and end_lvl which will check the depth of menu and replace the class name.
That’s all there is to it! Hope this solution will solve your problem and helpful to you.Stay tuned with creativedev for more information 🙂