The WordPress Theme Sidebar Template

Update: We’ve created a second edition of this article, with updated code samples and coverage of the latest theme development techniques. Check it out at The WordPress Theme Sidebar & Footer Templates. It’s part of The ThemeShaper WordPress Theme Tutorial: 2nd Edition.

I know you’ve been waiting patiently for this one. Everybody loves the Sidebar Template. But we’re going to do ours a little differently than everyone else.

Ours is going to be better.

Custom Sidebar Functions

First things first. With a WordPress Sidebar Template, we need to make sure it’s widgetized. Ours is going to have two widget areas. That way we can re-use this code for 2-column or 3-column themes (on a 2-column theme the sidebars are stacked, one on top of the other).

This is pretty straightforward. In our functions.php file we’re going to register our widget areas with the following code.

// Register widgetized areas
function theme_widgets_init() {
	// Area 1
	register_sidebar( array (
		'name'          => 'Primary Widget Area',
		'id'            => 'primary_widget_area',
		'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
		'after_widget'  => '</li>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>',
  	) );

	// Area 2
	register_sidebar( array (
		'name'          => 'Secondary Widget Area',
		'id'            => 'secondary_widget_area',
		'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
		'after_widget'  => '</li>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>',
  	) );
} // end theme_widgets_init

add_action( 'init', 'theme_widgets_init' );

Now we’ve got two widget areas: Primary Widget Area and Secondary Widget Area. There’s no point naming them Primary Sidebar or Secondary Sidebar. In some layouts they might not even be sidebars—but they’ll always be widget areas.

Now, still in functions.php we’re going to add two more super-cool custom code snippets.

Firstly, we’re going to pre-set our default widgets: The Search, Pages, Categories, Archives, Links and Meta Widgets. We won’t be coding them in manually to sidebar.php. We’ll be telling WordPress to add them to our dynamic widget area in the settings (thank Ptah Dunbar for this).

$preset_widgets = array (
	'primary_widget_area'   => array( 'search', 'pages', 'categories', 'archives' ),
	'secondary_widget_area' => array( 'links', 'meta' )
);
if ( isset( $_GET['activated'] ) ) {
	update_option( 'sidebars_widgets', $preset_widgets );
}
// update_option( 'sidebars_widgets', NULL );

Now, in our Primary Widget Area (primary_widget_area) we’ve got the Search Widget, the Pages Widget, the Categories Widget, and the Archives Widget. The Secondary Widget Area (secondary_widget_area) has the Links and Meta Widgets. They’re all loaded up there in our WordPress options, ready and waiting.

Did you see // update_option( 'sidebars_widgets', NULL ); in the last line? Uncomment that line if you need to reset your widgets for any reason. As I’m sure you can guess, NULL means no widgets.

Now secondly, we’re going to create a new conditional that will check to see if there are any widgets in a given widget area. This will be incredibly useful (with props to Chaos Kaizer) when we code up our Sidebar Template.

// Check for static widgets in widget-ready areas
function is_sidebar_active( $index ){
	global $wp_registered_sidebars;

	$widgetcolums = wp_get_sidebars_widgets();

	if ( $widgetcolums[$index] ) return true;

	return false;
} // end is_sidebar_active

Now we need to put these custom code snippets to work.

Coding The Sidebar Template

With our dynamic widget areas registered and pre-set widgets, our Sidebar Template is going to be one of the simplest templates you’ll ever see. But remember, we’re also going to want to wrap our sidebars in an IF statement using our new conditional is_sidebar_active().

Here’s what it’ll look like:

<?php if ( is_sidebar_active('primary_widget_area') ) : ?>
		<div id="primary" class="widget-area">
			<ul class="xoxo">
				<?php dynamic_sidebar('primary_widget_area'); ?>
			</ul>
		</div><!-- #primary .widget-area -->
<?php endif; ?>

<?php if ( is_sidebar_active('secondary_widget_area') ) : ?>
		<div id="secondary" class="widget-area">
			<ul class="xoxo">
				<?php dynamic_sidebar('secondary_widget_area'); ?>
			</ul>
		</div><!-- #secondary .widget-area -->
<?php endif; ?>

Now if you go into the widget admin page and pull all those widgets out of any one of those widget areas the conditional statement guarding the markup will fail. Big time. And to our benefit. No widgets. No markup. Dead simple.

Just the way we like things around here.

How To Create a WordPress Theme

This post is part of a WordPress Themes Tutorial that will show you how to create a powerful WordPress Theme from scratch. Read it from the beginning and code yourself up something awesome.

  1. WordPress Theme Tutorial Introduction
  2. Theme Development Tools
  3. Creating a Theme HTML Structure
  4. Template and Directory Structure
  5. The Header Template
  6. The Index Template
  7. The Single Post, Post Attachment, & 404 Templates
  8. The Comments Template
  9. The Search Template & The Page Template
  10. The Archive, Author, Category & Tags Template
  11. The Sidebar Template
  12. Reset-Rebuild Theme CSS & Define Your Layouts

69 thoughts on “The WordPress Theme Sidebar Template

  1. mathieu Ab says:

    there is this code at the end of the index.php code

    div id=”primary” class=”widget-area” /div
    !– #primary .widget-area –
    div id=”secondary” class=”widget-area” /div
    !– #secondary –

    is that to be erased ? i guess so.

  2. mathieu Ab says:

    the search and link widget don’t show on the page. they are actived by default. they keep being in the desactived section of the widget panel in the admin menu. can’t actived them…

  3. There’s a new function in WordPress 2.8 that checks to see if the sidebar has active widgets: is_active_sidebar(). You should probably use that just in case anything changes to the API.

    Love the idea of stacked sidebars, perfect for those ever changing layouts.

    • I was going to use Ian’s function in my theme, but then I saw Ptah’s comment. Only, is_active_sidebar() doesn’t seem to work for me. is_active_sidebar( 'Sidebar name' ) returns false, but dynamic_sidebar( 'Sidebar name' ) (in the same block of code) outputs the sidebar’s widgets fine. Any ideas?

  4. Well worth the wait young man. If in the USA, this kinda has firecrackers to it! 2 questions, 1 you already know.

    1. Can the preset widgets be changed? Say Ian Stewart, world renown author, make a new plugin and we want to add it to our presets.

    2. If all widgets are removed and the conditional fails, should we have something that displays saying ‘ Add widgets to this area’

    • You should probably leave your widget presets as core ones if you’re publicly releasing the Theme. If you’re using it for yourself across custom installs where you know Widget-X is going to be installed, by all means, yeah.

      Experience has taught me that it’s best to leave blank widget areas blank. If you don’t want something in there, “Add widgets to this area” gets old fast. :)

  5. mathieu Ab says:

    in the function preset part, in the if ( !isset ….
    is the ! correct or is it supposed to be just isset with !.

    we want to test if ‘activated’ is true , right ?

    • mathieu Ab says:

      ok, a little correction to my comment :
      (i am very bad at commenting apparently…)

      “is the ! correct or is it supposed to be just isset without the !. “

  6. Pingback: WordPress 主题之侧边栏模板 | 精品博客

  7. Brian Ngo says:

    After the presets are set, should we comment out that section of code? I noticed that if the code is left in, the new widget admin doesn’t play very well.

    What is the purpose of presetting them, anyways?

    Thanks for the guide, btw. While it doesn’t explain everything I need to know, it does give me a rough idea on where to start.

  8. Pingback: Wordpress theme készítés | Yloz féle zacc

  9. There is a bug in the code which presets widgets

    We should remove the ! from the condition which checks whether $_GET is set or not.

  10. patch says:

    Hi,

    Great tutorial on themes – and the layouts included top it off!
    Got a slight problem though, I cant get the sidebar ‘widget’ stuff to display at all.

    Both primary and secondary look just fine in the widget admin area – they seem to show what I would expect to see in the blog – but, the sidebar ‘widgets’ dont show up at all when viewing the site. Also, the wp_list_pages in the header just seems to ‘spit out’ the page list in a stream of connected text eg:
    page1page2page3 etc…. that right?

    here’s my sidebar.php

  11. First off, THANK YOU for this tutorial it is so valuable to finally have this out there so we/ I can learn how to set up a WP blog.
    I have to back up PATCH ^^ above, I am also unable to even get the sidebar and widgets to display. I have tried to look through the code and find the issue but am without any solutions. Any help? I have the widgets set up from the theme widget editor section.
    any help? thanks!!

    • I’ve got it working in my test setup (the setup I used when I went through the code myself, before I wrote the tutorial). And it works in the Thematic Theme. Strange.

  12. I will keep going over the code, there has to be something. Only thing is I think i followed your code tutorial quite strict. Ill keep you posted.
    Colin

    • I seem to be having the same issue. It was working fine on my test setup, but when I upgraded to 2.8.1, it wouldn’t come up. Then suddenly it started coming up on my test server, but won’t come up on my live server.

      • I’m going to take a hard look at this and see if I can figure out what’s what. (of course, again, if anyone else takes a hard look at it …).

      • Yeah, this is what I’m looking for since ages. Thank you for that week of tutorials and the code, now I can REALLY learn how to make wordpress themes. You see, I want to create wordpress themes myself (but I’m a beginner, I’m just 17 years..).
        I have installed a test-environment in which I can develop my own themes and I installed this theme, but I have the samen issue: everything works, except for the sidebar.
        I hope you can fix it.
        Thanks again,
        Nout

      • Jeremy says:

        I just upgraded to 2.8.2 and similar to @Geoff the sidebar has disappeared after the upgrade. I can’t see it in my testing server though. I’ll be looking into it as well.

      • Mike Silver says:

        Did anybody find the solution to this? I cant get the sidebar working, its just empty on 2.8.2 and 2.8.4.

        Thanks!

  13. Hey man,

    Fantastic Tutorial. Kinda New to wordpress and found this explained alot of things about WP layout and structure.

    I am having a problem however. I cant get either primary or secondary Widget areas to display. I am running layest WP version 2.8.1

    Any help would be much apreciated

    • I have been trying to get something to work all weekend. The best I could do is get two bars display in the first primary widget area. I have manipulated the CSS structure, moved things around and tried to compare the code to that of working themes (Although I am a beginner at WP design this helped a lot). I am staying tuned to see if there are any fixes that come out.
      Colin

  14. Terrence says:

    Ok, I figured out a work around I think.

    1)First thing is to delete the “!” (exclamation mark) from the $_GET['activated]‘ condition which Sudar mentioned above.
    2)Remove the widgets within the admin section and then move back the ones you want.

    Important: If you do step 2 before step 1, everything gets reset again and your widgets won’t show up. You will then have to repeat step 2 again.
    I’m using v 2.8.1 and have them showing up now.

  15. Terrance, nice job. It gets the sidebar active for me as well. Sometimes when i refresh it forgets which ones to keep active and in the correct spot. but, it is working now.
    thanks!

    • The solution is given above by Sudar and Terrence. It worked fine with me:

      “1)First thing is to delete the “!” (exclamation mark) from the $_GET[‘activated]’ condition which Sudar mentioned above.
      2)Remove the widgets within the admin section and then move back the ones you want.”

  16. As always, great tips Ian. Thank you!

    I just stumbled on a problem that (I believe) didn’t exist in WP 2.7 – some time ago I released a small plugin Advanced Text Widget – it shows content only on selected pages. Let’s say we’re using 1st Subsidiary Aside to show recent blog posts only on the home (index) page. In WP 2.8+ it outputs empty sidebar wrapper for the pages where widget is not supposed to appear. I tested it with my own theme and your latest Thematic. The code is identical to what you shown in the “Coding The Sidebar Template” section of this post.

    One would expect there would be helper function to is_active_sidebar() to check if there is an actual output and only then return true. But the way this function works, it just checks an associative array of active widgets, and has no idea if they have a true output.

    I hope you can follow my puzzle here. I would appreciate any input from you and if you think there could be a solution.

    Thanks again!

  17. I just realized, I might be wrong about WP 2.7 – I think I had multiple widgets with conditional appearance in a single sidebar and at least one widget was active on every page. So there was no telling if sidebar wrappers were there all the time and they would be empty if set my widgets only appear on selected pages.

    As an example of what I’m talking, check this post and this post. The Text Formatting Post is set to show top widget in a Single Top sidebar just on that particular post. The second page (Best 10 Daytrips) – has empty wrapper in the Single Top area. That’s my problem.

    • I hate the fact that WP echoes everything directly in the code – widgets, plugins everything is simply echoed. I’m not a programmer, so I don’t really know the reasons behind this technique… but already saw some widgets and functions with additional argument to get output or return value and it’s a lifesaver for me. I think it would allow WP to be more modular. Anyway, end of rant. Here is my temporary solution for checking if the widget (Advanced Text Widget) actually returns any values.

      /*
      ** Intercepts output buffer (echoed content) and returns it via variable
      ** if empty - trurnes false.
      */
      function _ob_get_contents_dynamic_sidebar($sidebar_name){
      ob_start();
      dynamic_sidebar($sidebar_name);
      $out = ob_get_contents();
      ob_end_clean();
      $out = rtrim(trim($out), "t");
      if($out){
      return $out;
      }
      return;
      }

      Then in the sidebar-x.php we ca do the following:

      if ( is_sidebar_active($sidebar_name) && $output = _ob_get_contents_dynamic_sidebar($sidebar_name)) {
      echo ''. "n" . '' . "n";
      echo $output;
      echo '' . "n" . ''. "n";
      }

      This seem to be working for now in my own theme. Would be nice to figure out how to implement it within the plugin, so people don’t have to edit their sidebar templates. The concern that I have it that the function I came up with was return some spaces and tabs, even though there was no real content.. that way it was coming out as True. So I had to trim the white-spaces and tabs to make sure they don’t show up… and it works. But have a feeling it might be a loophole for similar things to pop-up that won’t be trimmed out while there is still no real content. Not totally sure about it.

  18. Hi,

    Just thought I’d point out that the function (located in widgets.php) is_active_sidebar($index) does not work (WordPress 2.8.3) if $index is the name of the widget. However, using an integer representing the true index in the sidebar-registration array, this function works as it is supposed to.

    I use the function in a hand-coded left sidebar which has a different div id depending whether there are any widgets actually in the sidebar.

    Cheers!

    • Mike Silver says:

      Thanks Chris, but can you give at specific fix, so us noobs can get it working again!?

      Thanks again,

      Michael

  19. Pingback: Wordpress Wednesday: 50 Links & Resources from around the web | Wordpress Guerrilla

  20. Pingback: Build WordPress Sites Fast With the Thematic Theme Framework | Es Developed - Fresh Website and Graphic Design

  21. hi,

    for what is worth, when no widgets show up in the theme’s sidebar(s) though they’re present in the dashboard’s widget panel, just remove one widget from the panel and the others will activate by themselves.

  22. I have followed this tutorial word for word and have looked at the coding in google docs but I I cannot get the sidebar widgets to show up on the site. Is there something that I am not doing?

  23. Pingback: How To Create a WordPress Theme: The Ultimate WordPress Theme Tutorial « Social Media Greece

  24. Pingback: How To Create a WordPress Theme!?!?! « Designdefine's Blog

  25. mariana says:

    too much copy+paste on the fly but this whole tutorial works fine for me,
    looking forward to start playing around ‘my-theme’
    thank you
    greetings from fr

  26. Meroko says:

    I don’t see an ! mark in that code? And also the sidebars will not show up and frequently the theme will just stop letting me edit at all unless I remove the functions.php. Confused and would love any possible help. Is there a full copy of all the pages anywehre I could look at?

  27. First 3 words : THANK YOU and WAOW !
    This sum up my feelings. You can not imagine how much you help me to figure out and finally understand a WP “skeleton” if I may say so.
    So I am now designing, playing, and really enjoying my time with this tut. I am almost there, but in my quest for fun ;-) I want a widget area in the footer and as a beginner in Php, I bump into small problem and wonders.
    To achieve this, I miss clues :
    In function.php I created an area 3 as follow
    register_sidebar( array (
    'name' => 'Footer Widget',

    etc…
    AT this point , the footer appears in the wp widget section !!
    question : do I have then to code the following part ( in functions.php)
    // Pre-set Widgets
    $preset_widgets = array (
    OR is it done for the functions.php file ?
    THEN 2nd question :
    do I have to interact with the sidebar.php ?
    or do I edit only the footer.php ?
    ( no need to say that css has to edited ;-) )
    Besides, I am also checking the thematic forum for this, but I want to be sure that I do things right…
    I hope my comment is clear…english is not my mother tongue.
    Thank you again and again and again….
    Cheers

  28. Hey Ian
    First of all, thanks for the amazing tutorial. I’m having a very hard time though, as I’m not a designer and have rarely had any contact with PHP.
    Right now, my blog and template look all wrong, but my doubt is this: I don’t see any widgets on the side columns. I suppose the widget areas are two sidebars if I’m using 3c-b.css, right?
    And I have no idea where to start looking for the problem ‘=(

    Oh, and your functions.php is missing the ?> at the end, that was erasing the entire output! ‘=)
    Thanks again, man!

  29. Rachel says:

    Thank you, thank you thank you! Loved it, this is going to help me much. Also amazing, yours is one of the few tutorials I found that the code is actually a code and not a screen shot. I am blind, so now I can give my first shot at my theam. I already sort of know how to code css and HTML, but now I want to learn to make a theam in wordpress, but I thought I had to learn PHP before I could start! I do have a quick question, if I want to make a global horizontal nav bar do I have to make a separate php file for that, or can it go on my header file? thanks again!

  30. Eric H says:

    This is great, thanks Ian. One question for you. What’s the best way to add more sidebars throughout the theme and retain the ability to remove the main sidebars on certain pages? For example I’ve created a sidebar in the header and 3 in the footer. On certain pages I want to remove the primary and secondary widgets but keep the header and footer widgets. I know I can remove all widgets, do I need to create separate functions for the new widgets, or is there a better way?

  31. StevieG says:

    This is an excellent tutorial – so easy to follow with just the right amount of guidance. I’m following it all and loved the idea of preset widget areas. However, it doesn’t work for me. I decided to download Shape and take a look at your code there but that doesn’t show preset widgets either just a blank area. What obvious step am I missing??

  32. I’m building my first WP theme from this tut and I think it’s great. I had the same problem as many others have with the widgets, but like has been stated, if I

    1. remove ! from the line: ” if ( !isset( $_GET['activated'] ) ) { ” in functions.php
    2. remove all the widgets in the admin area, the add them back in

    It works like a charm.

    Thanks for the great tutorial series and thanks to everyone who has posted about their problems and the fixes.

  33. For some reason I can’t get the sidebar to show up. I’ve even downloaded all the php files you’ve uploaded to the code library and attempted to use that (I assume that’s what my files should look in there final state) but they also don’t seem to show the sidebar widgets. Any ideas?

  34. Hi Ian.
    First off, thanks a million for this excellent tutorial – it’s a really great way to get to grips with WP theme development from the groud up!

    Secondly, I also had the problem of the missing sidebar widgets (the one Terrence supplied the solution to). However, the solution didn’t work for me at first, and now I know why:

    In one of your comments above, you mention that we have to uncomment the “//update_option( ‘sidebars_widgets’, NULL );” line in functions.php.

    If you do this, and then follow Terrence’s solution, it won’t work.

    So you have to re-comment the “//update_option( ‘sidebars_widgets’, NULL );” line, and then follow Terrence’s solution – this worked for me!

    Thanks again, and good luck everyone else with this!

  35. Pingback: Test Test Test for best results in Wordpress | yfenni.net

  36. Pingback: psdtoowp.com » Blog Archive » Registering New Sidebars for Custom Page Templates The Smart Way

  37. Pingback: psdtoowp.com » Blog Archive » Thematic 0.9.6.1 Is Live

  38. Mark Gilvey says:

    Is there a link to all of these files somewhere? I have gone through the tutorial but all I get is a blank page. I am not worthy. Ultimately, I’m a designer, I just want to understand the CSS and how to make it all look different. Having all the files where I’m not trying to pretend I can code this would be best at this point.

    From the reading I’ve done my understanding is In Dreamweaver, I could just replace the words your-theme with the name of what I want the title of the them to be.

    I don’t want this to come off as though I’m not trying. I spent the entire afternoon on this and was hoping it would work but I’ve failed. As mentioned, I would ultimately like to be able to implement designs with this wonderful and well thought out series of files.

  39. First and foremost….I know nothing about .php and thanks to this tutorial I’ve now got a WP site up and running on Apache.

    It’s not much at the moment but it’s a good start.

    Secondly, I got the side bar to appear just by deleting the widgets in the admin section and puting them back in again. I didn’t have to mess with the code. So maybe the code has been fixed.

    I took two attempts at the tutorial to get it all working.

    Any road up…thanks for the info! :-)

Comments are closed.