We are going to make WordPress menu int bootstrap menu by walker class. first define class and called walker following code in function.php file

class submenu_wrapper extends Walker_Nav_Menu {
// add classes to ul sub-menus
function start_lvl( &$output, $depth = 0, $args = array() ) {
// depth dependent classes
$indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent
$display_depth = ( $depth + 1); // because it counts the first submenu as 0
$classes = array(
/* 'dropdown-menu left-1'*/
'dropdown-menu'
);
$class_names = implode( ' ', $classes );
// build html
if ($display_depth == 1) {
$output .= "\n" . $indent . '<ul class="' . $class_names . '">' . "\n";
} else {
$output .= "\n" . $indent . '<ul class="' . $class_names . '">' . "\n";
}
}
}
After the extending walker class, we will add classes and attribute in anchor tag by “nav_menu_link_attributes” Filter. for a you have to use it as per following code.
add_filter( 'nav_menu_link_attributes', 'anchor_menu_add_class', 10, 4 );
function anchor_menu_add_class( $atts, $item, $args ,$depth=0) {
if ($args->walker->has_children==1 && $depth === 0 ) {
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
$atts['data-toggle'] = 'dropdown';
$atts['class'] = 'dropdown-toggle';
$atts['aria-haspopup'] = 'true';
$atts['aria-expanded']='false';
} elseif($depth === 0) {
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
$atts['class'] = '';
} elseif($depth === 1) {
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
$atts['class'] = 'dropdown-item';
}
/*if($depth === 0) {
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
$atts['class'] = 'nav-link';
}elseif ($args->walker->has_children==1 && $depth === 0 ) {
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
$atts['data-toggle'] = 'dropdown';
$atts['class'] = 'nav-link dropdown-toggle';
$atts['aria-haspopup'] = 'true';
$atts['aria-expanded']='false';
} elseif($depth === 1) {
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
$atts['class'] = 'dropdown-item';
}*/
// print_r($args->walker->has_children);
//echo "<pre>";
// print_r($item);
//die;
return $atts;
}
Calling walker In header.php
<?php
echo wp_nav_menu(array('menu'=>'Home Menu','menu_class'=>'navbar-nav ml-auto','walker'=>new submenu_wrapper,'container'=>false));
?>
0 Comments