Bootstrap v5 wp-bootstrap-navwalker dropdown navbar not work

Viewed 4393

I use Bootstrap v5 and [wp-bootstrap-navwalker][1]

in function.php

<?php
  require_once('class-wp-bootstrap-navwalker.php');
  function main_menu(){
    wp_nav_menu(array(
      'theme_location'    => 'main-menu',
      'menu_class'        => 'nav navbar-nav',
      'depth'             => 2,
      'container'         => 'div',
      'container_class'   => 'collapse navbar-collapse',
      'container_id'      => 'navbarSupportedContent',
      'fallback_cb'       => 'WP_Bootstrap_Navwalker::fallback',
      'walker'            => new WP_Bootstrap_Navwalker(),
    ));
  }
?>

in header.php

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="container">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <?php main_menu() ?>
  </div>
</nav>

the dropdown menu not work
[1]: https://github.com/wp-bootstrap/wp-bootstrap-navwalker

1 Answers

Bootstrap 5.0.0 [ 2021 ]

Tested and Working ✔

You can use this function. This will update data-toggle to data-bs-toggle.

add_filter( 'nav_menu_link_attributes', 'bootstrap5_dropdown_fix' );
function bootstrap5_dropdown_fix( $atts ) {
     if ( array_key_exists( 'data-toggle', $atts ) ) {
         unset( $atts['data-toggle'] );
         $atts['data-bs-toggle'] = 'dropdown';
     }
     return $atts;
}

Source: https://github.com/wp-bootstrap/wp-bootstrap-navwalker/issues/499

Fixing the Hamburger icon dropdown

OP already using the new navbar elements. But if any of you using the old one and updated only the functions from above, then follow the steps below.

In responsive the Hamburger icon will not work if you are using the old classes. You also have to update your from data-toggle to data-bs-toggle

<button ... data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" ...>
   <!--span-->
</button>
Related