Tag Archives: twitter

Using Twitter Bootstrap Dropdown Menus with WordPress

 

02/17/12 – Updated! Click here for the latest code. After some testing, there were a few fixed to clean up the HTML.

01/12/12 – All fixed, see my new post: Update #2: Using Twitter Bootstrap Dropdown Menus with WordPress

01/11/12 – I’ve since found a better way to handle these and posted a new post here.


Bootstrap is a toolkit from Twitter designed to kickstart development of webapps and sites.
It includes base CSS and HTML for typography, forms, buttons, tables, grids, navigation, and more. – twitter.github.com/bootstrap

I love Twitter’s Bootstrap toolkit. I’ve used it a few times now and I look for every excuse to play around with it. When I use a toolkit like Bootstrap, I really try to leave the toolkit alone and free of modifications. One problem with trying to use Bootstrap and WordPress together is getting the html correct. This goes for a number of things, but doubly for menus. If your html is not correct, the css rules will not take effect and you’ll be left with an unstyled bit of blah.

For example: to use a dropdown menu with Bootstrap, you need to add a
data-dropdown="dropdown" attribute to the appropriate <li> element.

This may not be the best way, but here’s how I did it.
WordPress puts together structured information like this using a “Walker” class. For a menu, that Walker is Walker_Nav_Menu. We will want to extend that class in order to modify how it puts the menu together. Then we’ll make sure that we specify our custom walker when we display our menu.

Here’s we’ll extend the standard walker and add the data-dropdown="dropdown", as well as the neccessary dropdown-toggle class to the link. It goes in your functions.php file.

class Bootstrap_Walker_Nav_Menu extends Walker_Nav_Menu {

function start_lvl( &$output, $depth ) {

$indent = str_repeat( “\t”, $depth );

$li_finder = ‘

    1. jQuery
    2. bootstrap-dropdown.js
    3. script.js

    This is because your script relies on bootstrap.js, which in turn relies on jQuery.

    As anyone will tell you, it’s best practice in situations like this to place your javascript right before your </body> tag.

    There are likely more efficient ways to extend the Walker class, but this is a somewhat less-hacky way than what I’ve seen done. The nice thing is that it works with the stock Bootstrap CSS and there’s no need to do anything in the WordPress backend other than structure your menus as you usually would. It could easily be made into a plugin, I suppose… but it’s a pretty specific, contextual thing.

%d bloggers like this: