Proper WordPress menus with Bootstrap 4

Bootstrap 4 has come a long way, but it doesn't fit inside of WordPress all that well.

Categories: Frontend, WordPress

One common struggle with WordPress is the integration of menus with different front-end frameworks like Bootstrap. Making them work out of the box is impossible and requires some goofing around. In this article, I will show you how to make some simple adjustments to your menu that will allow you to easily style them with Bootstrap 4.

The common go-to for me over the years has been the Bootstrap Navwalker.

With the latest beta release, it was finally time to see what it would take.

Bootstrap 4, unfortunately, needed a few more classes to properly work. The list items needed nav-item and the links needed to have nav-link added.

For quick reference, Here is a sample block that I use to create the main menu.

wp_nav_menu(array(
    'menu'           => 'main-menu',
    'theme_location' => 'main-menu',
    'menu_id'        => 'navigation',
    'depth'          => 3,
    'container'      => false,
    'menu_class'     => 'nav',
    //Process nav menu using our custom nav walker
    'walker'         => new wp_bootstrap_navwalker()
));

Let’s start by opening your functions.php file and adding these filters.

add_filter('nav_menu_css_class', 'add_classes_on_li', 1, 3);
function add_classes_on_li($classes, $item, $args)
{
    $classes[] = 'nav-item';

    return $classes;
}

add_filter('wp_nav_menu', 'add_classes_on_a');
function add_classes_on_a($ulclass)
{
    return preg_replace('/<a /', '<a class="nav-link"', $ulclass);
}

These filters regardless of what you use for your menus will insert the class names in the generated HTML.

The end result should be a menu that properly supports Bootstrap 4’s menu system!

If you need a little more help with building a Nav using the Bootstrap Navwalker have a look here.

If you are looking for more control over your menu, but you will only go one level deep. I wrote a quick post about how to get Full control over WordPress menus. This came it helpful when listing post types in a sidebar. Think Products or services.

If you are looking for tips on how to create
Bootstrap centred nav menus or for Full control over WordPress menus check out those posts.

Adam Patterson

Adam Patterson

User Interface Designer & Developer with a background in UX. I have spent 5 years as a professionally certified bicycle mechanic and ride year-round.

I am a husband and father of two, I enjoy photography, music, movies, coffee, and good food.

You can find me on Twitter, Instagram, and YouTube!