May 23rd, 2019
I came across an issue while building a site for my high school’s ASB, which was how to deal with the limited amount of navbar space while my clients wanted to have lots of links.
I was already using WP-Bootstrap-navwalker, which allows you to implement WordPress’s menus in your Bootstrap 4 themes, but according to several issues opened about this same topic, that only allows you to do single layer dropdowns.
The fix only requires code edits or additions in 3 places and is relatively easy to perform.
First, in your styles.css file or wherever you have your main styles, add the following code:
.dropdown-submenu { position: relative; } .dropdown-submenu .dropdown-menu { top: 0; left: 95%; margin-top: -1px; } @media (max-width: 992px) { .dropdown-menu { padding: .5rem 0; margin: .125rem 0 0; } li > ul > li > ul > li > .dropdown-item { padding: .25rem 3rem; } li > ul > li > ul > li > .dropdown-item:before { content: '• '; } }
Then,
Wherever your theme has the wp_nav_menu() function, change or add the depth option as follows:
'depth' => 3, // 1 = no dropdowns, 2 = with dropdowns, 3 = multilevel dropdowns.
It is usually 2 but to allow for more sub menus, set it to 3.
Finally, you’re going to need a bit of javascript to get the menus to work. inline it using a <script> tag or add it to an existing linked js file:
$(document).ready(function(){ $('.dropdown-menu > li > .dropdown-menu').parent().addClass('dropdown-submenu').find(' > .dropdown-item').attr('href', 'javascript:;').addClass('dropdown-toggle'); $('.dropdown-submenu > a').on("click", function(e) { var dropdown = $(this).parent().find(' > .show'); $('.dropdown-submenu .dropdown-menu').not(dropdown).removeClass('show'); $(this).next('.dropdown-menu').toggleClass('show'); e.stopPropagation(); }); $('.dropdown').on("hidden.bs.dropdown", function() { $('.dropdown-menu.show').removeClass('show'); }); });
This should be all that’s needed to create multi-level dropdown navigation menus in bootstrap!
Thanks to ikender on Github for this quick fix!
There is still a bug with this in that if you have more than one drop down, when you mouse off and/or go to click another top level srop down, the previous drop remains open.
Interesting, I’m not able to reproduce this on my end in the sites that have this live. Are you able to send me a proof of concept where this occurs?
Really Thank you so much, I was struggling to find the answer for the last 4-5 days. Finally, I found it here. This is really amazing. Thank you.
This was a huge help! Thanks for sharing. First time in years I’ve been asked to make a multi level menu for someone, and as we use Bootstrap 4, there’s nothing built in for this option. Your code helped me get to where I needed! Thanks!
Absolutely, I’m not sure why it’s not built-in to bootstrap at this point but I remember it took me a while of digging to get it to work for me so I figured I’d post it in case anyone else found it useful!