CCDzine
6/3/2017 - 12:09 AM

Get the number of widgets in a WordPress sidebar.

Get the number of widgets in a WordPress sidebar.

<?php
/*
 * Count sidebar widgets by ID
 */
function ccd_widget_count_class( $params ) {
	$sidebar_id = $params[0]['id'];
  
  // Your sidebar ID
	if ( $sidebar_id == 'sidebar-widgets' ) {
		$total_widgets = wp_get_sidebars_widgets();
		
		// First part of str_replace is the exact string to be replace
		$sidebar_widgets = count( $total_widgets[$sidebar_id] );
		
		// Add a widget-count-X class to widget wrapper
		$params[0]['before_widget'] = str_replace( 'class="widget sidebar-widget', 'class="widget sidebar-widget widget-count-' . $sidebar_widgets . ' ', $params[0]['before_widget'] );
	}
  
  // Apply filter to the output in case it's needed for child theming
	$count_class = apply_filters( 'ccd_footer_widget_count_class', $params );
	return $count_class;
}
add_filter( 'dynamic_sidebar_params', 'ccd_widget_count_class' );

Get Number of Widgets

WordPress Snippet