Kategoriarkiv: Bootstrap

nav

How to build a WordPress collapsible subpages menu with Bootstrap

I like Bootstrap and I like WordPress, so it’s a really good day for me when I get to combine the two. Which I’ve had the opportunity to do on a recent project we’re doing. I could go on and on about the possibilities of this awesome CSS framework and I probably will at some point, but right now I thought I’d share how I used the collapsible accordion in Bootstrap to display a particular page’s sub-pages including one level of hierarchy. A picture of the end result:

nav

Requirements

Bootstrap’s collapsible requires its own JavaScript, which in turn requires jQuery, so make sure you enqueue both of those in your functions.php . Here’s how I added bootstrap.js :

Of course the  bootstrap.css  is also necessary.

Function for creating the Bootstrapified subpage list

The markup for the accordion differs a lot from what you get when wp_list_pages is called, so I had to do a custom function to list all the pages hierarchically. What I wanted in the end was to list children and grandchildren of the root page. This meant I had to find the oldest parent and then create the markup to list its children. I also had to find all the children of each of the previous children and create the correct markup for those. But in this case that was it, only two levels of navigation was needed.

Here’s the function I ended up with in my functions.php :

I build the resulting markup step by step by first creating the surrounding elements. Next step is to fetch the correct pages, and I only wanted the first level of pages that was children to the root page, no grandchildren were wanted.

It’s the argument 'parent'=>$oldest_parent that determines that only direct descendants are retrieved.

In the two nestled foreach-loops the different pages’ HTML is rendered. Different markup is created depending on if there are granchildren or not. The counter is to make sure that there are unique IDs on the panels.

 Displaying the result

Short and easy:

Making it look pretty

Arguably the most important part. I wrote it in LESS syntax, but the resulting CSS can be found here. This adds all-CSS triangles to act as arrows and makes them fancy and rotatey.

And that’s it. Hope it’s of use for all y’all internetz people. Give a shout if something is odd, to praise me or correct me, or if you have questions =)

Want to create a navigation menu using Bootstrap’s navigation? I recommend the wp-bootstrap-navwalker, it’s worked out great for us!