Bootstrap Multi Level Dropdown Menus in WordPress

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!


Comments

Comments Are Not Yet Implemented.