The WordPress Theme Sidebar Template

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.

  1. // Register widgetized areas
  2. function theme_widgets_init() {
  3.  // Area 1
  4.  register_sidebar( array (
  5.  'name' => 'Primary Widget Area',
  6.  'id' => 'primary_widget_area',
  7.  'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
  8.  'after_widget' => "</li>",
  9.  'before_title' => '<h3 class="widget-title">',
  10.  'after_title' => '</h3>',
  11.   ) );
  12.  
  13.  // Area 2
  14.  register_sidebar( array (
  15.  'name' => 'Secondary Widget Area',
  16.  'id' => 'secondary_widget_area',
  17.  'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
  18.  'after_widget' => "</li>",
  19.  'before_title' => '<h3 class="widget-title">',
  20.  'after_title' => '</h3>',
  21.   ) );
  22. } // end theme_widgets_init
  23.  
  24. 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).

  1. $preset_widgets = array (
  2.  'primary_widget_area'  => array( 'search', 'pages', 'categories', 'archives' ),
  3.  'secondary_widget_area'  => array( 'links', 'meta' )
  4. );
  5. if ( isset( $_GET['activated'] ) ) {
  6.  update_option( 'sidebars_widgets', $preset_widgets );
  7. }
  8. // 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.

  1. // Check for static widgets in widget-ready areas
  2. function is_sidebar_active( $index ){
  3.   global $wp_registered_sidebars;
  4.  
  5.   $widgetcolums = wp_get_sidebars_widgets();
  6.    
  7.   if ($widgetcolums[$index]) return true;
  8.  
  9.  return false;
  10. } // 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:

  1. <?php if ( is_sidebar_active('primary_widget_area') ) : ?>
  2.   <div id="primary" class="widget-area">
  3.    <ul class="xoxo">
  4.     <?php dynamic_sidebar('primary_widget_area'); ?>
  5.    </ul>
  6.   </div><!– #primary .widget-area –>
  7. <?php endif; ?>  
  8.  
  9. <?php if ( is_sidebar_active('secondary_widget_area') ) : ?>
  10.   <div id="secondary" class="widget-area">
  11.    <ul class="xoxo">
  12.     <?php dynamic_sidebar('secondary_widget_area'); ?>
  13.    </ul>
  14.   </div><!– #secondary .widget-area –>
  15. <?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

Don't forget: You should follow me on twitter here.

Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

43 Comments

  1. mathieu Ab
    Posted July 6, 2009 at 6:57 am | Permalink

    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
    Posted July 6, 2009 at 7:40 am | Permalink

    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…

    • mathieu Ab
      Posted July 6, 2009 at 7:59 am | Permalink

      when i add a widget in one of the side bar in the admin panel, it get put in the desactived widget when i reload the page. don’t know why…

      • Posted July 7, 2009 at 1:42 pm | Permalink

        I’m having the same problem as the above… can’t add or remove widgets to the sidebar.

    • Posted July 10, 2009 at 6:39 pm | Permalink

      Did you try resetting your widgets with update_option( 'sidebars_widgets', NULL );? Works for me.

  3. Posted July 6, 2009 at 7:42 am | Permalink

    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.

    • Posted July 10, 2009 at 6:40 pm | Permalink

      Thanks for the heads up, Ptah. Looks like I have to make with the neater code.

    • Posted July 13, 2009 at 8:36 am | Permalink

      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. Posted July 6, 2009 at 9:09 am | Permalink

    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’

    • Posted July 10, 2009 at 6:43 pm | Permalink

      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. Posted July 6, 2009 at 5:06 pm | Permalink

    Another Gem of a tutorial.
    Again, greatly appreciated.

  6. mathieu Ab
    Posted July 7, 2009 at 6:07 am | Permalink

    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
      Posted July 9, 2009 at 4:13 am | Permalink

      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 !. “

  7. Brian Ngo
    Posted July 7, 2009 at 6:18 pm | Permalink

    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.

    • Posted July 10, 2009 at 6:49 pm | Permalink

      The purpose of presetting is to have something there on first install. There’s no need to comment it out, no.

  8. Posted July 8, 2009 at 8:12 am | Permalink

    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.

    • Posted July 10, 2009 at 7:45 pm | Permalink

      Thanks for the heads up!

      • Posted July 22, 2009 at 1:59 pm | Permalink

        Hi Ian,
        you should correct this litle bug in the Google Code, ’cause it sure made me loose a lot of time. But anyway, thanks for the theme. I’m designing now my first child theme based in this one and it’s going very well. The dinamic categories give it great versatility.

      • Posted July 22, 2009 at 6:16 pm | Permalink

        I’ll second that comment.

  9. patch
    Posted July 11, 2009 at 12:27 pm | Permalink

    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

  10. Posted July 11, 2009 at 11:36 pm | Permalink

    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!!

    • Posted July 12, 2009 at 9:25 am | Permalink

      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.

  11. Posted July 12, 2009 at 9:33 am | Permalink

    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

    • Posted July 13, 2009 at 7:27 am | Permalink

      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.

      • Posted July 13, 2009 at 9:52 am | Permalink

        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 …).

      • Posted July 13, 2009 at 12:30 pm | Permalink

        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
        Posted July 20, 2009 at 8:55 am | Permalink

        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
        Posted August 17, 2009 at 3:55 am | Permalink

        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!

  12. Posted July 13, 2009 at 8:03 am | Permalink

    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

    • Posted July 13, 2009 at 8:58 am | Permalink

      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

  13. Terrence
    Posted July 14, 2009 at 10:34 am | Permalink

    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.

  14. Posted July 14, 2009 at 9:14 pm | Permalink

    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!

    • Posted July 22, 2009 at 2:04 pm | Permalink

      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.”

  15. Posted July 22, 2009 at 3:10 pm | Permalink

    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!

  16. Posted July 22, 2009 at 3:23 pm | Permalink

    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.

    • Posted July 23, 2009 at 10:24 am | Permalink

      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.

  17. Posted August 6, 2009 at 8:25 pm | Permalink

    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
      Posted August 17, 2009 at 3:32 am | Permalink

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

      Thanks again,

      Michael

  18. brian
    Posted August 28, 2009 at 3:13 pm | Permalink

    where is the donation page??

    u had a donation page asking people to give you 100 bucks…

  19. Posted December 25, 2009 at 9:05 pm | Permalink

    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.

  20. Posted December 31, 2009 at 8:27 am | Permalink

    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?

    • matchstic
      Posted January 9, 2010 at 9:51 pm | Permalink

      There is a fix described in the response above from Terrence :)

4 Trackbacks

  1. [...] 原文:The WordPress Theme Sidebar Template [...]

  2. By Wordpress theme készítés | Yloz féle zacc on July 8, 2009 at 8:04 am

    [...] The Sidebar Template [...]

  3. [...] The wordpress theme sidebar template [...]

  4. [...] Editing the Sidebar Template [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

By submitting a comment here you grant this site a perpetual license to reproduce your words and name/web site in attribution. In addition, you may find yourself fitter, happier and more productive. Comment away.

Subscribe without commenting