Skip to content

Instantly share code, notes, and snippets.

@zaynali53
Last active June 14, 2021 18:04
Show Gist options
  • Select an option

  • Save zaynali53/9e41e1e01b602148c394914e91b2a6be to your computer and use it in GitHub Desktop.

Select an option

Save zaynali53/9e41e1e01b602148c394914e91b2a6be to your computer and use it in GitHub Desktop.
Bootstrap Nav walker class for wp_nav_menu
<?php
class Bootstrap_Nav_Walker extends Walker_Nav_Menu {
public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$active = in_array( 'current-menu-item', $item->classes ) ? 'active' : '';
if ( in_array( 'menu-item-has-children', $item->classes ) ) {
$output .= "
<li class='nav-item dropdown'>
<a
href='{$item->url}'
class='nav-link dropdown-toggle'
role='button'
data-bs-toggle='dropdown'
aria-expanded='false'
>
{$item->title}
</a>
";
}
else {
if ( (int) $item->menu_item_parent === 0 ) {
$output .= "
<li class='nav-item {$active}'>
<a class='nav-link' href='{$item->url}'>{$item->title}</a>
";
}
else {
$output .= "
<li>
<a class='dropdown-item' href='{$item->url}'>{$item->title}</a>
";
}
}
}
public function start_lvl( &$output, $depth = 0, $args = null ) {
$output .= "<ul class='dropdown-menu'>";
}
}
<?php
wp_nav_menu([
'theme_location' => 'primary',
'menu_class' => 'navbar-nav',
'walker' => new Bootstrap_Nav_Walker
]);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment