Creating breadcrumb menus with wp_nav_menu

Do you want a breadcrumb menu in your WordPress theme? Are you using the native WordPress 3.0 menu functionality (wp_nav_menu) and reluctant to resort to a plugin when you’re already managing the menu through the built in menu manager? If the answer is yes, then this is for you.

When searching for a solution to this problem (which is admittedly pretty easy to solve) all the info I ran into suggested using various plugins. I didn’t really want to go that route because most of these plugins required you to manage your menu hierarchy within the plugin’s settings menu. This can get pretty tedious if you’re already managing your menu hierarchy through WordPress’ built in ‘Menus’.

Here is a quick and easy way to do it using the built in nav menu.

Step 1

The first step involves simply calling wp_nav_menu as you would call it any other time. For my purposes I only specified 2 menu levels “array( ‘depth’ => ‘2’)“. You could omit this and have a menu that expands more levels but you’d have to tweak your css accordingly.

The above code simply implements a 2 level menu based on the menu you created in the ‘Menus’ area of the admin panel. Without any further coding you’ll get a mess that looks something like this (depending on the how many items you have in your menu).

unstyled-menu

Step 2

In the next step we simply use css to hide everything. We do this so we can later selectively display the items we want to show.

.tn-title li{
  display: none;
}

This will leave you with something that looks like this.

hiddem-menu

Step 3

In the final step we’ll override the css that hid everything and get it to show specific items. WordPress adds a lot of useful classes to the menu elements but the ones of interest for us are current-menu-item and current-menu-ancestor. The implementation of these classes is probably self evident; current-menu-item is added to the li that corresponds to the current page and current-menu-ancestor is applied to every item in the hierarchy from the current item until it’s parent/grandparent on the first level of the menu.

Here is how the css looks;

#breadcrumb-menu .tn-title li.current-menu-item,
#breadcrumb-menu .tn-title li.current-menu-ancestor{
   display: list-item;
   float: left;
}

#breadcrumb-menu .tn-title li.current-menu-item a{
   font-weight: 500;
}

Basically, we’re-displaying the current menu item and all it’s ancestors. The second style makes the current item bold, this is totally optional. Notice that these rules include the div (#breadcrumb-menu), this is important because we need to make these rules more specific than the earlier rules we used to hide the entire menu. If these rules don’t have greater specificity the menu items will simply stay hidden (you could get by this by using !important but increasing specificity is generally the preferred method)

The end result will look something this;

finished-menu