Tomoro Logo

WordPress Walker for Bootstrap 4 with dropdown menus

Building on top of Simon Padbury’s code, the following Nav Walker will only add dropdown specific classes if your menu has a depth greater than 1. So if you use the same menu in your header and footer, but only want dropdowns in the header, you’re in luck! No need to hide the down-arrow with CSS.

class Bootstrap_4_Walker extends \Walker_Nav_Menu {
    
    function start_lvl(&$output, $depth = 0, $args = array()) { // ul
        $indent = str_repeat("\t",$depth); // indents the outputted HTML
        $submenu = ($depth > 0) ? ' sub-menu' : '';
        $output .= "\n$indent
    \n"; } function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ){ // li a span $indent = ( $depth ) ? str_repeat("\t",$depth) : ''; $li_attributes = ''; $class_names = $value = ''; $classes = empty( $item->classes ) ? array() : (array) $item->classes; $classes[] = ($args->depth > 1 && $args->walker->has_children) ? 'dropdown' : ''; $classes[] = ($item->current || $item->current_item_anchestor) ? 'active' : ''; $classes[] = 'nav-item'; $classes[] = 'nav-item-' . $item->ID; if( $depth && $args->walker->has_children ){ $classes[] = 'dropdown-menu'; } $class_names = join(' ', apply_filters('nav_menu_css_class', array_filter( $classes ), $item, $args ) ); $class_names = ' class="' . esc_attr($class_names) . '"'; $id = apply_filters('nav_menu_item_id', 'menu-item menu-item-'.$item->ID, $item, $args); $id = strlen( $id ) ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . '
  • '; $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr($item->attr_title) . '"' : ''; $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr($item->target) . '"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr($item->xfn) . '"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr($item->url) . '"' : ''; $attributes .= ( $args->depth > 1 && $args->walker->has_children ) ? ' class="nav-link dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"' : ' class="nav-link"'; $item_output = $args->before; $item_output .= ( $depth > 0 ) ? '' : ''; $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after; $item_output .= ''; $item_output .= $args->after; $output .= apply_filters ( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } }

Then call your menu with…

 'primary_navigation', 
      'container'      => false,
      'menu_class'     => 'navbar-nav',
      'fallback_cb'    => '__return_false',
      'items_wrap'     => '
    %3$s
', 'depth' => 2, 'walker' => new Bootstrap_4_Walker() ) ); endif; ?>