Beginner’s Guide To WordPress Menus & Bootstrap Navigation

Learn how to use Bootstrap's navigation with WordPress Menus.

20th August 2016

beginners-guide-to-wordpress-menus-and-bootstrap-navigation

Twitter Bootstrap is an incredibly popular front-end framework due to its ease of use and the speed in which you can get a web application up and running. It’s no surprise that many WordPress themes are now being built with Bootstrap; however, getting the WordPress menu editor to work with Bootstrap’s default navigation isn’t as simple as just including the relevant Bootstrap CSS and JavaScript files. With the help of some navigation walkers, we can get WordPress menus and Bootstrap navigation working harmoniously together.

Please note, if you are working on an existing theme, then please do make a backup of your theme’s files in case anything goes wrong.

Actually Creating a Menu

Before we can start thinking about getting the Bootstrap navigation to work, we need to make sure we actually have a menu we can use. If you already have a menu set up in your WordPress admin, then you can skip this part and move on to including the required Bootstrap files into your theme, otherwise read on.

Register a Menu

First things first, we need to register the name of our menu. Open up the functions.php file of your theme and add the following code:

function register_header_menu() {
  register_nav_menu('header-menu',__( 'Header Menu' ));
}
add_action( 'init', 'register_header_menu' );

Defining Your Menu

We now need to define a menu within the WordPress Menu Editor. Go ahead and login to your admin and go to Appearance > Menus.

Click on the text field Menu Name and name your new menu. This can be anything you want, but it should really be something that makes sense regarding the items are included in the menu.

create-menu-1

Add Items to Your Menu

Add some items to your menu using the various options on the left. Once you have finished adding all of the items you would like to your menu, tick the checkbox ‘Bootstrap Menu’ under menu locations and then click Save Menu. Your menu is now created and linked with a menu location.

create-menu-2

If you would like to know more about using the WordPress menu editor, then you can read the official documentation here.

Including Twitter Bootstrap into Your WordPress Theme

If we’re going to be using the Twitter Bootstrap navigation then we will need to include the relevant files within our theme. There are a number of ways to do this; we can either use the Bootstrap JavaScript and CSS files hosted on CDNs or we can download the files and save them within our theme’s files.

You can download the Bootstrap files at getbootstrap.com or you can use the following CDN hosted files:

Required Bootstrap CSS file

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

An optional Bootstrap theme CSS file

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

Required Bootstrap JavaScript file

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous">

If you really want to, you can simply include these files directly within your template files, e.g. the styles within the document head in your header.php file and the JavaScript file before the closing body tag in your footer.php file; however, it’s recommended to do this the WordPress way by enqueuing these styles and scripts. You can read the official WordPress documentation about enqueuing styles and scripts here.

To enqueue these files you will need to edit your functions.php file. If you want to use the Bootstrap CDNs use the following code snippet:

// The CSS files for your theme
function theme_styles() {
    wp_enqueue_style('bootstrap-css', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css', array(), '', 'all');
    wp_enqueue_style('bootstrap-theme', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css', array('bootstrap-css'), '', 'all');
}

// The JavaScript files for your theme
function theme_js() {
    wp_enqueue_script( 'bootstrap-js', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js', array('jquery'), '', true );
}

add_action( 'wp_enqueue_scripts', 'theme_styles' );
add_action( 'wp_enqueue_scripts', 'theme_js' );

If these files are hosted on your own domain, e.g. within /js/ and /css/ directories within your theme, then you can load them like so:

// The CSS files for your theme
function theme_styles() {
    wp_enqueue_style('bootstrap-css', get_template_directory_uri . '/css/bootstrap.min.css', array(), '', 'all');
    wp_enqueue_style('bootstrap-theme', get_template_directory_uri . '/css/bootstrap-theme.min.css', array('bootstrap-css'), '', 'all');
}

// The JavaScript files for your theme
function theme_js() {
    wp_enqueue_script( 'bootstrap-js', get_template_directory_uri . '/js/bootstrap.min.js', array('jquery'), '', true );
}

add_action( 'wp_enqueue_scripts', 'theme_styles' );
add_action( 'wp_enqueue_scripts', 'theme_js' );

We have used the get_template_directory_uri() function here to return your theme’s URL. If you are using a child theme and the Bootstrap CSS and JavaScript files are stored there, you will want to use get_stylesheet_directory_uri() instead to return the child theme’s URL.

Save your functions.php file and then reload any page on your site. You should now see the Bootstrap CSS files loading in the document head and the JavaScript Bootstrap file loading just before the closing body tag.

With that complete we’re ready to begin making Bootstrap’s navigation work with WordPress menus.

Bootstrap Nav Walker for WordPress

Out of the box Twitter Bootstrap doesn’t work with WordPress menus. To get the two working well together, your theme will require a walker. Luckily, Edward McIntyre (AKA Twittem) has already created one that works and is very easy to set up. You can find his Bootstrap Navwalker here.

Including Edward Mcintyre’s WP Bootstrap Navwalker into Your Theme

Download the ZIP file of WP Bootstrap Navwalker from GitHub and extract this file. Copy and paste the wp_bootstrap_navwalker.php file into your theme’s main directory. We then need to include this PHP file in our functions.php before we actually do anything with our menus.

Open your functions.php and add this code:

// Register Custom Navigation Walker
require_once('wp_bootstrap_navwalker.php');

Setting up WP Bootstrap Navwalker

We are now going to create a quick function that we can call from within our theme, where we want this Bootstrap navigation to appear. Just below where we added the above code to include wp_bootstrap_navwalker.php, add the following lines of code:

// Bootstrap navigation
function bootstrap_nav()
{
	wp_nav_menu( array(
            'theme_location'    => 'header-menu',
            'depth'             => 2,
            'container'         => 'false',
            'menu_class'        => 'nav navbar-nav',
            'fallback_cb'       => 'wp_bootstrap_navwalker::fallback',
            'walker'            => new wp_bootstrap_navwalker())
    );
}

What we have done here is add a new argument walker to wp_nav_menu(). This creates a new instance of the wp_boostrap_navwalker object. You can find out more about wp_nav_menu() over at the official documentation.

Adding Bootstrap Navigation Markup

Now we need to actually call the bootstrap_nav() function from within our theme. In this scenario we will be adding this menu to our header.php file. Below is the code that you need to add to your header.php file where you want the Bootstrap navigation to appear:

<nav class="navbar navbar-default">
	<div class="container-fluid">
		<div class="navbar-header">
			<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
				<span class="sr-only">Toggle navigation</span>
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
			</button>
			<a class="navbar-brand" href="#">Project name</a>
		</div>
		<div id="navbar" class="navbar-collapse collapse">
			<?php bootstrap_nav(); ?>
		</div><!--/.nav-collapse -->
	</div><!--/.container-fluid -->
</nav>

What you are doing here is adding the markup for Bootstrap navigation and calling the function bootstrap_nav() that you just created in functions.php. Whatbootstrap_nav() is doing is creating an unordered list of the WordPress menu items with the correct Bootstrap markup.

N.B. this code should really replace any navigation and logo that you currently have in your header.php file. Of course you are free to modify this as you see fit, e.g. you may want two menus within your website’s header.

If you now go and reload a page on your site, you should see the new Bootstrap navigation there with the menu items pulled in from your WordPress menu. Excellent!

bootstrap-menu-1

If you want to have a dropdown of menu items, go back to the WordPress menu editor and drag the child menu items below the desired parent menu item. Save this menu and then reload the page on your site and you should now see a dropdown menu. Please note that Bootstrap 3 does not support dropdown sub-menus.

bootstrap-menu-2

bootstrap-menu-3

How about we take this one step further and look at creating Bootstrap mega menus that work with WordPress menus?

Bootstrap Mega Menus for WordPress

Bootstrap’s navigation now works with WordPress menus, but how do we go about creating mega menus with this set up? Well, there is a great project on GitHub called YAMM 3 which makes it really simple to create mega menus for Bootstrap.

YAMM Nav Walker for YAMM 3

For us to get the markup right for the navigation to use YAMM 3, we need to include another nav walker. For this we can use Ryan McDonald’s YAMM Nav Walker which you can download here.

Including Ryan Mcdonald’s YAMM Nav Walker in WordPress

Including YAMM Nav Walker is a straightforward process and exactly the same as how we added Edward McIntyre’s WP Bootstrap Navwalker. Download the ZIP file of YAMM Nav Walker and copy and paste the yamm-nav-walker.php file into the main directory of your theme.

Edit your theme’s functions.php file where we used the require_once() function for wp_bootstrap_navwalker.php and change it to this:

// Register WP Bootstrap Navwalker
require_once('wp_bootstrap_navwalker.php');

// Register YAMM Navigation Walker
require_once('yamm-nav-walker.php');

Setting up YAMM Nav Walker

Now we have YAMM Nav Walker included in our theme’s functions.php file, we need to make use of this new navigation walker. Just below where we added thebootstrap_nav() function in our functions.php file, add the following code:

// Bootstrap mega menu navigation
function bootstrap_megamenu_nav()
{
	wp_nav_menu( array(
        'theme_location'    => 'header-menu',
        'depth'             => 4,
        'container'         => 'div',
        'container_class'   => 'collapse navbar-collapse',
        'container_id'      => 'bootstrap-navbar-collapse-1',
        'menu_class'        => 'nav navbar-nav yamm',
        'fallback_cb'       => 'Yamm_Nav_Walker_menu_fallback',
        'walker'            => new Yamm_Nav_Walker())
    );
}

We now have a menu setup to create an instance of the Yamm_Nav_Walker object instead of the wp_bootstrap_navwalker object.

Add Another Level of Items to Your Menu

In the WordPress Menu Editor add another level of menu items to your menu and click Save Menu. These will be the lists of links within your mega menu.

mega-menu-1

Including YAMM 3 for WordPress

Download the ZIP file for YAMM 3 here, then copy and paste the yamm.css file into the directory where you have all of the CSS files in your theme e.g. /yourtheme/css/. We can now include this CSS file in our theme by using wp_enqueue_styles().

Open your theme’s functions.php file and edit the theme_css() function we created earlier to also include yamm.css:

// The CSS files for your theme
function theme_styles() {
    wp_enqueue_style('bootstrap-css', get_template_directory_uri . '/css/bootstrap.min.css', array(), '', 'all');
    wp_enqueue_style('bootstrap-theme', get_template_directory_uri . '/css/bootstrap-theme.min.css', array('bootstrap-css'), '', 'all');
    wp_enqueue_style('yamm', get_template_directory_uri . '/css/yamm.css', array('bootstrap-theme'), '', 'all');
}

Save your functions.php file and then refresh a webpage of your site. You should now see yamm.css being included within the source code.

Setting up YAMM 3

You can view a demo of YAMM 3 here to see the various types of mega menu you can create. In our example, if you go into your WordPress admin and create a multi-level menu down to 3 levels, you’ll see that it doesn’t look particularly pleasing to the eye. It would probably be best to edit the list styling.

mega-menu-2

Bootstrap provides us with an easy way to change the list styling just by adding the class list-unstyled to a ul element. You could go into your yamm-nav-walker.php file and add the class list-unstyled to the relevant ul element in there; however, this change will get overwritten whenever you update this plugin.

A better option is to simply update your style.css to set the list-style to none. For the ul elements that we want to style, Yamm Nav Walker has added a classelementy-ul. We can use this class to easily change the list styling. Open your style.css file and create the following CSS rule:

.yamm ul.elementy-ul {
    list-style:none;
    max-width:120px;
    padding-left:0;
}

If you now reload your webpage, you should see that the list items are all nicely aligned on the left without any bullet points.

mega-menu-3

Of course, you can style these mega menus however you like. For example, you might want to add a media query that adds a bottom margin between each of the ulelements when viewing the menu on mobile:

@media screen and (max-width: 767px) {
    .yamm ul.elementy-ul {
        margin-bottom:25px;
    }
}

mega-menu-4

Creating a Mega Menu Plugin to Be Used Across Multiple Themes

Ok, so we can create standard WordPress menus with a drop down and Bootstrap and we can create mega menus with Bootstrap, but what if you wanted to use this across multiple themes quite often? Well instead of having to copy and paste this code into each theme’s functions.php file, we can just create a WordPress plugin.

The following is an example of a really simple plugin you can build to easily integrate Bootstrap navigation with your WordPress themes.

Create Your Plugin

First things first, we need to create a folder to place all of our plugin files. Go to your plugin directory and create a folder called bootstrap-nav-megamenu or whichever name you prefer.

Copy and paste the wp_bootstrap_navwalker.php and yamm-nav-walker.php files into this directory. Create a sub-directory called CSS and copy yamm.css into this directory, then create a file called bootstrap-nav-megamenu.php in the main directory for this plugin.

In the file bootstrap-nav-megamenu.php add the following block of code:

<?php
defined('ABSPATH') or die("No script kiddies please!");
/*
Plugin Name: Bootstrap Nav Megamenu
Plugin URI:  http://www.yourdomain.com/
Description: Easily integrate Bootstrap menus and megamenus with WordPress
Version:     0.1
Author:      Your Name
Author URI:  http://www.yourdomain.com/
License:     GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/

// Register WP Bootstrap Walker
require_once('wp_bootstrap_navwalker.php');

// Register YAMM Navigation Walker
require_once('yamm-nav-walker.php');

// Bootstrap navigation
function bootstrap_nav()
{
	wp_nav_menu( array(
        'theme_location'    => 'header-menu',
        'depth'             => 2,
        'container'         => 'false',
        'menu_class'        => 'nav navbar-nav',
        'fallback_cb'       => 'wp_bootstrap_navwalker::fallback',
        'walker'            => new wp_bootstrap_navwalker())
    );
}

// Bootstrap mega menu navigation
function bootstrap_megamenu_nav()
{
	wp_nav_menu( array(
        'theme_location'    => 'header-menu',
        'depth'             => 4,
        'container'         => 'div',
        'container_class'   => 'collapse navbar-collapse',
        'container_id'      => 'bootstrap-navbar-collapse-1',
        'menu_class'        => 'nav navbar-nav yamm',
        'fallback_cb'       => 'Yamm_Nav_Walker_menu_fallback',
        'walker'            => new Yamm_Nav_Walker())
    );
}

// Load YAMM styles
function bootstrap_mega_menu_styles()
{
	wp_register_style('yamm', plugin_dir_url(__FILE__) . 'css/yamm.css', array('bootstrap-theme'), '', 'all');
	wp_enqueue_style('yamm'); // Enqueue it!
}

add_action('wp_enqueue_scripts', 'bootstrap_mega_menu_styles'); // Add YAMM Stylesheet

This is essentially combining all of the code that we created in the previous sections and placing it within our plugin. A change we have made here is that we have created two different functions for creating wp_nav_menu(); one for just a normal Bootstrap navigation and one that uses YAMM mega menus.

To include either of these navigation menus within your theme; add either of these code snippets where you would like your navigation to appear.

<?php bootstrap_nav(); ?>

for the standard Bootstrap navigation or

<?php bootstrap_megamenu_nav(); ?>

for the YAMM mega menu.

If you reload your web page after calling one of the above functions in one of your theme’s templates, then you should now see your Bootstrap navigation showing up.

Adding Images to Your Mega Menu

We have our Bootstrap mega menu working and we have it set up as a plugin, but it doesn’t look particularly great, as it is just separate lists of text (just text may actually look great depending on how you style it!). What if we want to add images to each of our menu items? Luckily there is a plugin already out there that can take care of this for us, Menu Image by Zviryatko.

Download the Menu Image plugin to your plugins directory and activate it. Once you have done this, if you visit the Menu Editor you should be able to see some new options under each of the menu items in the menu you have already created.

menu-image-1

You can then select an image for each menu item and how that displays on the front-end. Once you have added some images and saved your menu, go back and reload one of your site’s pages. Voila! You should now see these images appearing alongside your menu items.

menu-image-2

Summary

Despite the fact that WordPress menus and Bootstrap navigation don’t work together out of the box, there resources available to make the task of combining the two much simpler. All that’s left now is to get creative and style your WordPress Bootstrap hybrid menu.

Resources

The Author: Daniel Lee

Daniel Lee

I’m a bit of a geek if I had to say so myself. I love web design & development and digital marketing. I’ve got quite a passion for conversion rate optimisation right now. I find the insights into your customers thoughts and behaviour fascinating.

22 Comments

  • Lee

    Lee(1 year ago)

    Reply

    A great tutorial! Finally got the bootstrap navigation to work with WordPress!

    • Daniel Lee

      Daniel Lee(1 year ago)

      Reply

      Glad you got it working!

  • osman

    osman(9 months ago)

    Reply

    hi!
    please help me.
    i have use this tricks but my mega menus dont work!

  • mike

    mike(9 months ago)

    Reply

    Wow that’s very helpful. Thanks a bunch !
    I get it to work however in my source code i noticed 2 divs are not closing :

    Any help would be appreciated 🙂

    • Ryan Macdonald

      Ryan Macdonald(9 months ago)

      Reply

      Hey Mike! Just a heads up, I finally got around to updating my walker. `div` tags are now properly closing.

      • Daniel Lee

        Daniel Lee(8 months ago)

        Reply

        Thanks for letting us know here Ryan 🙂

  • Dylan Nirvana

    Dylan Nirvana(9 months ago)

    Reply

    Tough times. Trying to get this to work with Bootstrap 4. The dropdowns just do not work.

    • Daniel Lee

      Daniel Lee(8 months ago)

      Reply

      Hi Dylan

      I’m thinking of creating my own walker for Bootstrap 4, but just finishing up a couple of other projects first. I’ll update on here once it’s done.

      • Emma

        Emma(2 months ago)

        Reply

        Hi Daniel,
        Thanks so much for this tutorial, it’s exactly what I have been scouring the web for for the past few days! Just wondering if you’ve completed the Bootstrap 4 version yet? 🙂

  • Enrico

    Enrico(9 months ago)

    Reply

    Thank you Daniel, this was really helpful.

  • Mario

    Mario(7 months ago)

    Reply

    Got it working with Bootstrap 4. Some renaming of classes in CSS stylesheet, but the functionality not too different to BS3.

  • Dale

    Dale(5 months ago)

    Reply

    Nice article dude!

  • Jeff

    Jeff(4 months ago)

    Reply

    what if i have multiple menus? how to customize with bootstrap? thank you!

  • Jeff

    Jeff(4 months ago)

    Reply

    what if i have a multiple menus, how to customize all the menus with bootstrap? thank you! jeff 🙂

  • Pierre

    Pierre(4 months ago)

    Reply

    Hello Dylan, thanks for your guide. That was really helpful and clear and my menu is up and running thanks to you. Thanks a lot! I’m wondering how I could implement 2 bootstrap navigation sections (one pulled left, the other pulled right) into WordPress so that I have two separate menus in WordPress. Any idea? Thank you and best wishes, Pierre

    • Pierre

      Pierre(4 months ago)

      Reply

      Sorry Daniel…not Dylan

  • William Dugger

    William Dugger(4 months ago)

    Reply

    I cant even get this to work with bootstrap 3 let alone 4. Seems you skipped a bunch of steps for the Yamm install Im stuck there. Dropdowns dont work for yamm at all.

    • William Dugger

      William Dugger(4 months ago)

      Reply

      Ok turns out you need a specific version of jquery, you didn’t mention this anywhere. It works but it’s just a mess. Is there no way to get custom normal nested menus in wordpress?

  • John Okosun

    John Okosun(4 months ago)

    Reply

    Hello

    I am getting an error when I add // Register Custom Navigation Walker
    require_once(‘wp_bootstrap_navwalker.php’); to my functions.

    it says
    Fatal error: require_once(): Failed opening required ‘wp_bootstrap_navwalker.php’ (include_path=’.;C:\php\pear’) in C:\wamp64\www\wptest\wp-content\themes\BT\functions.php on line 77

    I have downloaded the file from GitHub and added it to my theme root but still am getting that error.

    what should i do?

    • William Patton

      William Patton(2 weeks ago)

      Reply

      Hey John,

      At one point I updated the name of the walker file in the repo, this article has not been updated to reflect to the new name. Use `require_once ‘wp-bootstrap-navwalker.php’` instead.

  • IndiasJob

    IndiasJob(2 weeks ago)

    Reply

    Hello,

    Thank you for sharing your helping codes but I have no idea about coding and I am using WordPress theme website ” http://www.indiasjob.com“. I want to make responsive my website menu bar so please help me that how can use these codes and wherein WordPress.

    Thanks again and have a good day !!
    Indiasjob

Leave a Reply

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