Created
November 28, 2019 22:00
-
-
Save matrixwd/03146676dfc0962e1503d9773cc27bef to your computer and use it in GitHub Desktop.
Adds Bootstrap CSS classes dynamically based on how many widgets in Wordpress Footer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Register widget area. | |
* | |
* @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar | |
*/ | |
function mwd_widgets_init() { | |
register_sidebar( array( | |
'name' => __( 'Footer', 'understrap' ), | |
'id' => 'footerfull', | |
'description' => __( 'Full sized footer widget with dynamic grid', 'text-domain' ), | |
'before_widget' => '<div id="%1$s" class="footer-widget %2$s dynamic-classes">', | |
'after_widget' => '</div><!-- .footer-widget -->', | |
'before_title' => '<h3 class="widget-title">', | |
'after_title' => '</h3>', | |
) | |
); | |
} | |
add_action( 'widgets_init', 'mwd_widgets_init' ); | |
// Add Bootstrap column class to widgets | |
function mwd_widgets_count($params) { | |
global $sidebars_widgets; | |
/* | |
* When the filter runs it checks for changes | |
*/ | |
$sidebars_widgets_count = apply_filters( 'sidebars_widgets', $sidebars_widgets ); | |
// Only apply changes if sidebar ID is set and the widget's classes depend on the number of widgets in the sidebar. | |
if ( isset( $params[0]['id'] ) && strpos( $params[0]['before_widget'], 'dynamic-classes' ) ) { | |
$sidebar_id = $params[0]['id']; | |
$widget_count = count( $sidebars_widgets_count[ $sidebar_id ] ); | |
$widget_classes = 'widget-count-' . $widget_count; | |
if ( 0 === $widget_count % 4 || $widget_count > 6 ) { | |
// Four widgets per row if there are exactly four or more than six. | |
$widget_classes .= ' col-md-3'; | |
} elseif ( 6 === $widget_count ) { | |
// If two widgets are published. | |
$widget_classes .= ' col-md-2'; | |
} elseif ( $widget_count >= 3 ) { | |
// Three widgets per row if there's three or more widgets. | |
$widget_classes .= ' col-md-4'; | |
} elseif ( 2 === $widget_count ) { | |
// If two widgets are published. | |
$widget_classes .= ' col-md-6'; | |
} elseif ( 1 === $widget_count ) { | |
// If just on widget is active. | |
$widget_classes .= ' col-md-12'; | |
} | |
// Replace the placeholder class 'dynamic-classes' with the classes stored in $widget_classes. | |
$params[0]['before_widget'] = str_replace( 'dynamic-classes', $widget_classes, $params[0]['before_widget'] ); | |
} | |
return $params; | |
} | |
add_filter('dynamic_sidebar_params','mwd_widgets_count'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment