Dynamic Twitter Bootstrap columns for sidebars.

UPDATE: I am using this in more places than one so I did the practical thing and created a function to drop in functions.php. See the Gist link at the end of the article for the updated code.

I build most of my themes on Twitter Bootstrap which uses a 12 column grid system. You set column sizes using a CSS class, span# with # being the number of columns on the grid that element will span.

I was coding a footer for a new theme and the client wanted six columns so I started hard coding the structure. When I was putting in a check in for active sidebars I thought why would I want to display a blank column if nothing is going in it. So I wrote this code to check for how many active sidebars are going in a row and adjust the spans.

First setup your variables. $max_sidebars should never be higher than 12 for Bootstrap.

Find out how many sidebars are active for that row. I’m storing the ID of the sidebar in the $active_sidebars array so later I’ll know exactly which sidebars are active.

Now find what span# class to use based on the number of active sidebars. If there are no active sidebars I won’t even output the row so I set $span to blank. Everything above 7 will be set to 1 column and 5 active sidebars sets the span to 2. I know it would be more efficient to set the array count to a variable and just access that but I got lazy.

Now that we know what sidebars are active and how many the displaying part is pretty easy. If there are no active sidebars we won’t display the row at all. Other than that we just loop through each sidebar ID in the array and output the HTML. If the container only has the one row just move the conditional around all of it instead of just the row.

The full file is on Gist: https://gist.github.com/4218556

Leave a Reply