18 C

WordPress: how to add custom classes in wp_nav_menu using custom walker calass?

Sometimes we need to add custom classes in the the navigation menus created by wordpress’ function ‘wp_nav_menu’. For example we want to add custom classes for dropdown menus, in such spcific cases we there is no option to add custom class for dorpdown menu. So in that case we can use walker abstract class.
We will create a new class in functions.php extending wordpress class “Walker_Nav_Menu” of  “Walker” Class. We can set any name to our new walker class. i.e. Primary_Walker_Nav_Menu


Class: Primary_Walker_Nav_Menu in functions.php

// walker class to add custm classes in the header menu
class Primary_Walker_Nav_Menu extends Walker_Nav_Menu {

function start_lvl(&$output, $depth) {
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent<ul class=\"dropdown-menu\">\n";
    $output = str_replace("menu-item-has-children", "menu-item-has-children dropdown", $output);

Navigation Menu Function: wp_nav_menu

 $defaults = array(
              'theme_location'  => 'primary',
              'menu'            => '',  // name of the menu you created in the menus
              'container'       => '',
              'container_class' => '',
              'container_id'    => '',
              'menu_class'      => '',
              'menu_id'         => '',
              'echo'            => true,
              'fallback_cb'     => 'wp_page_menu',
              'before'          => '',
              'after'           => '',
              'link_before'     => '',
              'link_after'      => '',
              'items_wrap'      => '<ul id="{3b3dd3986446f2411a115859dfb9ef0645ca07550196603d49955fcfabeac62d}1$s" class="{3b3dd3986446f2411a115859dfb9ef0645ca07550196603d49955fcfabeac62d}2$s nav navbar-nav navbar-right menu">{3b3dd3986446f2411a115859dfb9ef0645ca07550196603d49955fcfabeac62d}3$s<li class="search"></li></ul>',
              'depth'           => 0,
              'walker'          => new primary_Walker_Nav_Menu() // this is the walker class we created to alter default menu html
             wp_nav_menu( $defaults );


- Advertisement -spot_img

More articles


Please enter your comment!
Please enter your name here

Latest article