Making Theme Widget Areas More Dynamic

While designing a new theme for a client a problem came up that has come up before. Making a horizontal area a widgetized area, ie the header area next to a logo. This could also be in the footer of a theme. Instead of hardcoded the widths of each widget and making the layout static, I decided to make it have dynamic widths. By dynamic I’m not just talking about using percentage widths, but making the widths dependent on how many widgets are added to the area. Luckily WordPress has a handy function that will give counts of all the widgets currently active and in which area they are active. The documentation on the function is quite sparse wp_get_sidebars_widgets

I used this function to roll my own reusable function.

function count_widgets($loc){
	$sidebar_widgets = wp_get_sidebars_widgets();
	$num_widgets = 0;
	foreach ( (array) $sidebar_widgets as $k => $v ){
		if ($loc != $k)
		if ( is_array($v))
			$num_widgets = $num_widgets + count($v);
	return $num_widgets;

Here’s is how it would be used. This is added in the header.php in the head section. What this does is get the number of widgets then divides 100 by this number then subtracts 2 times the number. The subtraction if for 1% left and right margin that is applied in the stylesheet. If more is required simply add the left and right together and multiply by the count. The .header_widget is the class that I used when registering the widget area. It is seen below.

<style type="text/css">
<?php $count = count_widgets('header');
$percentage = (100/$count) - ($count * 2);
echo '.header_widget{ width:' . $percentage . '%;}';

The parameter that is passed to the function is the id of the sidebar or widget area your getting the count for. To make sure what these values are it’s easiest to hardcode the ID when registering the sidebar. The before_widget applies the class that is used to change the width with the styles above.

  'name' => 'Header',
  'id' => 'header',
  'description' => 'Widgets will be shown in the header area.',
  'before_widget' => '<div class="header_widget">',
  'after_widget' => '</div>'

Another way would be to use print_r to view the contents of the output. Like this:

$sidebar_widgets = wp_get_sidebars_widgets();

This will output an array the keys will be the id that should be used.

About Jeremy Clark

Small town IT worker with interests in all things technological and technical. Biggest interests are in web development especially the WordPress publishing platform and the community supporting it. Currently developing and maintain the free WordPress theme Techozoic. I'm also always available for hire.
This entry was posted in wordpress and tagged , , , . Bookmark the permalink.

Leave a reply

Comments will be sent to the moderation queue.