The easiest way to do this is to use an off-the-shelf solution. There is a WP_Bootstrap_Navwalker class which extends WordPress’ native Walker_Nav_Menu class and makes your Navigation Menus ready for Bootstrap 3 or 4. Download it from GitHub.
Add it to your theme, then add the following to the functions.php
:
<?php
require_once('path-to-the-directory/wp-bootstrap-navwalker.php');
Change path-to-the-directory/
to fit your needs.
Next, alter your wp_nav_menu()
with the following code:
<?php
wp_nav_menu( array(
'menu' => 'header', // match name to yours
'theme_location' => 'header',
'container' => 'div', // no need to wrap `wp_nav_menu` manually
'container_class' => 'collapse navbar-collapse',
'container_id' => 'collapse-1',
'menu_class' => 'nav navbar-nav',
'fallback_cb' => false,
'walker' => new WP_Bootstrap_Navwalker() // Use different Walker
));
Note, that you don’t need the <div class="collapse navbar-collapse" id="collapse-1">
anymore as it will be added by wp_nav_menu()
with proper CSS classes and id
.
Also, read the WP_Bootstrap_Navwalker README.md file carefully.