How to add WordPress menu list separator for Bootstrap based Themes

This post quickly documents a method to add a list separator to a WordPress menu with Twitter Bootstrap based themes.

Print your WordPress menu in your theme’s template with something like this (note the link_after value):

wp_nav_menu( array(
    'theme_location' => 'primary', 
    'link_after' => '<li class="divider-vertical"></li>', 
    'menu_class' => 'nav') 
);

This will output HTML that looks something like this (I’ve removed the classes to clean it up):

<ul id="menu-primary" class="nav">
  <li><a href="http://www.yoursite.com/">Link</a></li>
  <li class="divider-vertical"></li>
  <li><a href="http://www.yoursite.com/">Link</a></li>
  <li class="divider-vertical"></li>
  <li><a href="http://www.yoursite.com/">Link</a></li>
  <li class="divider-vertical"></li>
</ul>

Note, if you add a character inside of the list tags WordPress’s walker will want to wrap it in an href tag essentially linking it, which isn’t really what we want in the menu.

Now, Bootstrap’s default styling for “divider-vertical” looks like this:

.navbar .divider-vertical {
height: 40px;
margin: 0 9px;
border-left: 1px solid #f2f2f2;
border-right: 1px solid #ffffff;
}

This works fine, but if you’re using a font-based menu the solid border used as a separator may look too harsh because it’s missing the aliasing that your menu’s fonts have.

To soften the separator you can use a pipe (|) character instead by adding some CSS:

.navbar .nav > li > a {
    float: none;
    padding: 10px 5px 10px;
    text-decoration: none;
    text-shadow: none;
}
.navbar .divider-vertical {
    margin: 9px 2px 0px 2px;
    border: none;
}
.navbar .divider-vertical:after {
    content: "|";
}
.navbar .nav > li:last-child {
    display: none;
}

This is primarily for CSS3 compliant browsers (see: last-child), but that was OK for my particular use case. The last two declarations above are what’s important. It prints a pipe character (|) after each list item with the class .divider-vertical (you added this in wp_nav_menu), and we just hide the last pipe charter with last-child.

I’ll probably catch hell for this because I’m adding content via CSS; so to make it as rock solid as possible you’d want to ideally write a filter for WordPress’s menu output, but it works across recent versions of each major browser, and degrades well enough.

Basically, that’s it. It’s a quick documentation of one of many, many methods for adding a menu separator for WordPress menus when using Twitter’s Bootstrap.

Post written by Ed Reckers

Founder and lead web development consultant at Red Bridge Internet : San Francisco WordPress Developers and Consultants.

One Response to “How to add WordPress menu list separator for Bootstrap based Themes”

  1. baidyanath

    It works fine but after using, the sub-menu not working. any width issue for sub menu?

Leave a Reply