< BACK TO BLOG

How to setup NavWalker for WordPress Menus

Published January 30, 2022

In this tutorial I will show you how to implement Navwalker in WordPress Menus. It is great to make your frontend connect with the panel so you don’t have to keep updating your code everytime someone needs to add a page to your menu. Instead, you can let WordPress handle the Menu assemble by just specifying the classes you want inside each element.

This is perfect to use on menus that display the active page. WordPress will handle all the logic behind the active page and will tag the active page with the classes you require, make the page stand out in the menu.

Enable Menus in your theme functions.php:

add_theme_support( 'menus' );

After that, add NavWalker class in your functions.php:

class Primary_Walker_Nav_Menu extends Walker_Nav_Menu { function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) { if (array_search('menu-item-has-children', $item->classes)) { $output .= sprintf("\n
  • %s\n", ( array_search('current-menu-item', $item->classes) ) ? ' class="nav-item current-menu-item"' : 'class="nav-item"', $item->url, $item->title ); } } function start_lvl(&$output, $depth) { $indent = str_repeat("\t", $depth); $output .= "\n$indent
      \n"; } }
  • Query the menu you created inside the panel passing its name:

    	$args = array(
     			'menu' => 'main',
    			'container'      => 'ul',
    			'menu_class'     => 'px-12 xl:flex items-center h-full hidden',
    			'walker'         => new Mobile_Walker_Nav_Menu()
    	); 
    

    Inside your menu component, add that to display the Menu pages that were added in the panel:

     wp_nav_menu( $defaults );

    After that you just replace the classes inside NavWalker Class inside functions.php to match the classes you have in your frontend code.


    Subscribe to my Newsletter

    Get the latest posts delivered right to your inbox

    Avatar of Author

    Taiguara Andrade

    Fullstack Developer and Writer at taiguaras.xyz


    © 2022 taiguaras