Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Adjusts Twitter Bootstrap columns in a single row based on the number active in WordPress for the area.
/**
* Adjusts Twitter Bootstrap columns in a single row based on the number active in WordPress for the area.
*
* This function will adjust the column spans in a row based on the number of sidebars that are active for that area.
* The maximum number of sidebars cannot be over 12 (the amount of columns in the Bootstrap grid). All the sidebars
* will need to have a common ID prefix (sidebar-1, sidebar-2, etc.).
*
* Usage: get_dynamic_sidebars( INT, STRING );
*
* @param integer $max_sidebars The maximum number of sidebars assigned to the row
* @param string $sidebar_prefix The common ID prefix these sidebars use
*/
function get_dynamic_sidebars( $max_sidebars, $sidebar_prefix ) {
// Check for valid parameters
if ( ( 12 >= $max_sidebars ) || ( '' != trim( $sidebar_prefix ) ) ) {
$active_sidebars = array(); // Array used to hold the sidebar IDs.
// Find the active sidebars place their IDs into the array.
for ( $i = 1; $i <= $max_sidebars; $i++ ) {
if ( ( function_exists( 'is_active_sidebar' ) ) && ( is_active_sidebar( $sidebar_prefix . $i ) ) ) {
$active_sidebars[ ] = $sidebar_prefix . $i;
}
}
$number_active = count( $active_sidebars ); // Get actual number of active sidebars.
// Find which span class to use
if ( 0 == $number_active ) {
$span = ''; // This is just here to avoid a division by 0 error.
} elseif ( 5 == $number_active ) {
$span = 'span2'; // 5 columns will always span2.
} elseif ( 7 <= $number_active ) {
$span = 'span1'; // Anything over 7 will always span1.
} else {
$span = 'span' . 12 / $number_active;
}
// Display the HTML
if ( ( 0 < $number_active ) && ( function_exists( 'dynamic_sidebar' ) ) ) {
echo '<div class="row">';
foreach ( $active_sidebars as $sidebar ) {
echo '<div class="' . $span . '">';
dynamic_sidebar( $sidebar );
echo '</div>';
}
echo '</div>';
}
}
}

giofilo commented Mar 11, 2013

Great code, thanks!
Do you know if is it possibile to write a "get_dynamic_widgets" version?
I mean: only one sidebar with class "row" and widgets of this sidebar with class "span-*".
I don't know if is it possible to determinate the number of widgets in a sidebar...

EDIT: Yes, it is possible: http://wordpress.stackexchange.com/a/54275

Owner

theantichris commented Jul 18, 2013

I feel like an ass. I never saw the alert for this comment.

Good find!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment