How to create a responsive menu using Bootstrap nav walker in WordPress

WordPress Snippets

To create a responsive WordPress menu using Bootstrap Nav Walker, you will need to follow these steps:

  1. Install and activate the Bootstrap Nav Walker plugin. This plugin provides a custom WordPress nav walker class that allows you to use the Bootstrap navbar in your WordPress theme.
  2. In your WordPress theme, create a new menu in the WordPress dashboard and assign it to a location.
  3. In your theme’s header.php file, add the following code to output the navbar:
// Responsive menu using Bootstrap nav walker
// More snippets at wpunplugged.com 

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">My Site</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNav">
    <?php
      wp_nav_menu( array(
        'theme_location'  => 'primary',
        'depth'           => 2,
        'container'       => false,
        'menu_class'      => 'navbar-nav',
        'fallback_cb'     => 'WP_Bootstrap_Navwalker::fallback',
        'walker'          => new WP_Bootstrap_Navwalker(),
      ) );
    ?>
  </div>
</nav>

This code will output a navbar using the Bootstrap Nav Walker plugin. The navbar will include a toggle button that allows the menu to be displayed on small screens.

  1. Make sure to include the Bootstrap CSS and JavaScript files in your theme. You can do this by adding the following lines to your theme’s functions.php file:
// Responsive menu using Bootstrap nav walker
// More snippets at wpunplugged.com 

function my_bootstrap_scripts() {
  wp_enqueue_style( 'bootstrap-css', 'https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css' );
  wp_enqueue_script( 'bootstrap-js', 'https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js', array('jquery'), '', true );
}
add_action( 'wp_enqueue_scripts', 'my_bootstrap_scripts' );

This will include the Bootstrap CSS and JavaScript files in your WordPress theme.

Share this post

You might also like...

Comment

Your email address will not be published. Required fields are marked *