You are here: Home » Extending WordPress » DIY WordPress: Creating Sidebars On-the-Fly in WordPress

DIY WordPress: Creating Sidebars On-the-Fly in WordPress

by Dave Doolin on November 30, 2009 · 13 comments

(Reading time: 6 – 10 minutes)

Website In A Weekend reader Kip Praslowicz is this week’s guest author. Kip goes into some detail on creating new sidebars.


This is a tutorial describing a method of configuring the back end of a Wordpress template so that any user can create new widget configuration areas via the wordpress admin panel, without ever having to edit any of the template’s php files.

This is a method I came up with to solve a problem with a small company’s corporate site I was working on. The Wordpress site being built was going to be very page centric, and would require multiple variations of the information in the side bar areas throughout the site. With the ultimate number of variations needed for their sidebar information being unknown, limiting the site to a set number of alternate sidebars seemed like a poor choice.

Should we predefine three sidebars? Five? Fifteen? How many duplicate page templates will be needed to handle all of these? The admin area is going to get very cluttered, and then what if they need more variants?

The solution I came up with for this problem was to use custom meta fields to define new sidebar areas on the fly where needed. It keeps the admin area as clean as possible, and provides a very large amount of scalability.

When all the coding changes for this method are finished, adding a new widgetized sidebar is as simple as follows.

  1. Clicking Edit this entry:
    Sidebar from Custom Fields 1
  2. Naming the new widget in a custom meta field:
    Sidebar from Custom Fields 2

  3. Configuring the widgets on the new sidebar:

    Sidebar from Custom Fields 3

  4. Admiring the awesome new sidebar:

    Sidebar from Custom Fields 4

Shall we get our hands dirty? Why of course! Configuring a template for this functionality can be done in three simple steps.

Naming your placements

For each widget placement in the template, you’ll need to pick an unique id for the placement’s default widgets, and a meta key which will be used to override the default widgets.

For this tutorial I am going to use a default id of default-right and a meta key of sidebar-right-alternative.

Registering the new widget areas

Open up the template’s functions.php file. In it you should find a few lines of code that will look like this.

1
2
3
4
5
6
7
8
if ( function_exists('register_sidebar') ) {
	register_sidebar(array(
		'before_widget' => '<li id="%1$s" class="widget %2$s">',
		'after_widget' => '</li>',
		'before_title' => '<h2 class="widgettitle">',
		'after_title' => '</h2>',
	));
}

The first thing we want to do is configure this code to register the default widgets for each placement in the template. This is done by adding the fields name and id to the array. Sticking with the default-right ID which I’ve chosen, the resulting code will appear as follows. Changes are in red.

1
2
3
4
5
6
7
8
9
10
 if ( function_exists('register_sidebar') ) {
	register_sidebar(array(
		'name'=>'Default Right Sidebar',
		'id' => 'default-right',
		'before_widget' => '<li id="%1$s" class="widget %2$s">',
		'after_widget' => '</li>',
		'before_title' => '<h2 class="widgettitle">',
		'after_title' => '</h2>',
	));
}

If you have multiple widget areas to define, just keep adding the register_sidebar() functions within the if statement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 if ( function_exists('register_sidebar') ) {
	register_sidebar(array(
		'name'=>'Default Right Sidebar',
		'id' => 'default-right',
		'before_widget' => '<li id="%1$s" class="widget %2$s">',
		'after_widget' => '</li>',
		'before_title' => '<h2 class="widgettitle">',
		'after_title' => '</h2>',
	));
	register_sidebar(array(
		'name'=>'Default Left Sidebar',
		'id' => 'default-left',
		'before_widget' => '<li id="%1$s" class="widget %2$s">',
		'after_widget' => '</li>',
		'before_title' => '<h2 class="widgettitle">',
		'after_title' => '</h2>',
	));
}

Now we need to add more code within the function_exists if statement to register any widgets we have defined in a custom meta field. To do so, add the following php code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	$query = "SELECT meta_value FROM $wpdb->postmeta 
				WHERE meta_key = 'sidebar-right-alternative' 
				GROUP BY meta_value ORDER BY meta_value ASC";
	$result = mysql_query($query);
	while($r = mysql_fetch_array($result)){
 
	   register_sidebar(array('name'=>$r['meta_value'],
			'id' => sanitize_title_with_dashes($r['meta_value']),
			'before_widget' => '<li id="%1$s" class="widget %2$s">',
			'after_widget' => '</li>',
			'before_title' => '<h2 class="widgettitle">',
			'after_title' => '</h2>',
	   ));	
 
	}

There are two points of interest in this code. First:

WHERE meta_key = 'sidebar-right-alternative'

Make sure to update the text in the quotes to match the meta key which will be used to specify new widget areas. If you are using more than one placements, the query needs to be written as follows with || statements to collect all the sidebars.

$query = "SELECT meta_value FROM $wpdb->postmeta
WHERE meta_key = 'sidebar-right-alternative'
|| meta_key = 'sidebar-left-alternative'
|| meta_key = 'alternate-footer_widgets'
GROUP BY meta_value ORDER BY meta_value ASC";

Second:

'id' => sanitize_title_with_dashes($r['meta_value']),

This creates an id for each widget area that is a sanitized version of the name you give it. Without this line of code present, Wordpress will fall back to the default method of creating Ids, which involves and incrementing id. Letting the widget areas being ID’d in this matter means that adding or removing a new widget area can cause all of the previously defined widgets shift from one widget area to the next. You don’t want that to happen, its very messy.

So, in your functions.php, the completed code will look like this if you are using one widget placement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
if ( function_exists('register_sidebar') ) {
	register_sidebar(array(
		'name'=>'Default Right Sidebar',
		'id' => 'default-right',
		'before_widget' => '<li id="%1$s" class="widget %2$s">',
		'after_widget' => '</li>',
		'before_title' => '<h2 class="widgettitle">',
		'after_title' => '</h2>',
	));
 
	$query = "SELECT meta_value FROM $wpdb->postmeta 
				WHERE meta_key = 'sidebar-right-alternative' 
				GROUP BY meta_value ORDER BY meta_value ASC";
	$result = mysql_query($query);
	while($r = mysql_fetch_array($result)){
 
	   register_sidebar(array('name'=>$r['meta_value'],
			'id' => sanitize_title_with_dashes($r['meta_value']),
			'before_widget' => '<li id="%1$s" class="widget %2$s">',
			'after_widget' => '</li>',
			'before_title' => '<h2 class="widgettitle">',
			'after_title' => '</h2>',
	   ));	
 
	}	
 
}

Displaying the new widgets

Now that the Wordpress engine is recognizing any new widget area you create, we need to edit the code to display these new areas if they exists. Open up your sidebar.php file. In it will be a section of code that looks like the following.

1
2
3
4
5
6
7
<?php
	if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar() ) : 
 
		<possibly a bunch of other php code & html>
 
	endif; 
?>

To make this code know to display any dynamically created widget areas, we need to modify it to look like this.

1
2
3
4
5
6
7
8
9
<?php 	
	$customSidebar = get_post_meta($post->ID, 'sidebar-right-alternative', true);
	if(!$customSidebar)
		$customSidebar = 'default-right';
 
	if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar($customSidebar) ) : 
 
	endif; 
?>

This code will query the post meta database looking for any alternate widget areas. If it doesn’t find any, it will then fall back to the default widget area. Make sure to update the strings to the meta key id, and default widget area ids in the code with whatever pair you have chosen for your site.

That is all it takes. You can now enjoy an infinite amount widget area configurations on your Wordpress site, without having to open up the php files every time you need a new one.

kip_praslowiczKip Praslowicz has spend the past five years doing web development within the powersports industry. During his free time he is a film photography advocate, and is currently working in the discipline of night photography.



Would you like more? Send me a letter...
"Hi Dave,
Website In A Weekend seems pretty cool. I'm serious about this WordPress and web stuff, and I'd like to keep up with it. My name is and my email address is . I'm comfortable with email newsletters. I know you will protect my privacy, and that I can unsubscribe at any time. "

{ 13 comments }

K. Praslowicz December 1, 2009 at 7:00 am

No comment. Just registering for e-mail notifications so I can help with any questions.
K. Praslowicz´s last blog ..Infrared Flash Photography With An Olympus XA2 My ComLuv Profile

Dr Wordpress! December 1, 2009 at 7:07 am

@K – Smart thinking! I’ll be promoting this for the next week everywhere CommentLuv is used, there will be traffic.
Dr Wordpress!´s last blog ..Stop It! Three Things to Stop Doing In Your PPC Campaign My ComLuv Profile

Josh December 1, 2009 at 4:36 pm

What an excellent, well written, engaging tutorial. Nice work Kip.

My only suggestion – and sorry if you did mention it above – would be to use a Child Theme to overwrite the files instead of editing them directly in the theme. If an update to the theme comes through (for example if you’re running a premium theme) the changes will get overwritten.

I’ll definitely bookmark this as a resource for future projects.

PS. You should think about turning this into a plugin!
Josh´s last blog ..Wordpress Plugin Highlights: How To Redesign Your Theme Without Distruping Your Live Website My ComLuv Profile

K. Praslowicz December 1, 2009 at 4:50 pm

Thanks for the compliments Josh.

Child theme would be a good idea for this. I tend to do all my development from the ground up instead of using a premium theme, so I often don’t even consider a third party doing a core update.

Gabe | freebloghelp.com December 2, 2009 at 9:07 am

Excellent info! I’m sure the winter months up north give you nice opportunities to code.
Gabe | freebloghelp.com´s last blog ..Theme itch – no blogger is immune My ComLuv Profile

Deacon December 2, 2009 at 9:41 am

Whoa. This one is meaty.

I’m gonna have to file this one away and dig into it on a rainy day.
Deacon´s last blog ..Thinking in Layers My ComLuv Profile

Dr Wordpress! December 2, 2009 at 12:41 pm

@Gabe – Basements are real popular in that part of the country.

@Deacon – You and me both.
Dr Wordpress!´s last blog ..Stop It! Three Things to Stop Doing In Your PPC Campaign My ComLuv Profile

Mike CJ December 2, 2009 at 12:49 pm

Wow! That’s a great in depth post. Unlike around 99% of bloggers I use Drupal, and these kind of things are much easier in Drupal, but sadly most regular stuff isn’t.

Dr Wordpress! December 2, 2009 at 12:55 pm

@Mike – I ran Drupal 4 for a while on a small business site. Nobody else was able to handle it… we would have been better off using Dreamweaver at that time.
Dr Wordpress!´s last blog ..Stop It! Three Things to Stop Doing In Your PPC Campaign My ComLuv Profile

Josh December 2, 2009 at 2:43 pm

@Mike & Dave – have you guys tried Joomla? It’s worth a look as well and is my fav go-to when a site gets a little far away from what Wordpress can handle.
Josh´s last blog ..Tweet Weekly Bulletin: I hope this pisses you off. My ComLuv Profile

K. Praslowicz December 30, 2009 at 5:02 pm

Woo-heee. I’m finally implementing my own tutorial onto my own web site.
K. Praslowicz´s last blog ..Zenith City – The Year In Street Photography 2009 My ComLuv Profile

Dr Wordpress! December 31, 2009 at 11:04 am

Send a link when you’re done, I’ll add it into the article and post an update. Or if you want to follow up with a short article and more info, that would be exceedingly cool too.
Dr Wordpress!´s last blog ..Life is Short. What Do You Have to Show for Yourself? My ComLuv Profile

B B Kent February 12, 2010 at 8:43 am

That’s very useful, thanks Kip. I need to create some custom database items for a client, and this looks like I will give me a way to display that info.
B B Kent´s last blog ..Deal My ComLuv Profile

Comments on this entry are closed.

Previous post:

Next post: