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.
- WordPress Theme Tutorial Introduction
- Theme Development Tools
- Creating a Theme HTML Structure
- Template and Directory Structure
- The Header Template
- The Index Template
- The Single Post, Post Attachment, & 404 Templates
- The Comments Template
- The Search Template & The Page Template
- The Archive, Author, Category & Tags Template
- The Sidebar Template
- Reset-Rebuild Theme CSS & Define Your Layouts
43 Comments
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.
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…
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…
I’m having the same problem as the above… can’t add or remove widgets to the sidebar.
Did you try resetting your widgets with
update_option( 'sidebars_widgets', NULL );? Works for me.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.
Thanks for the heads up, Ptah. Looks like I have to make with the neater code.
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, butdynamic_sidebar( 'Sidebar name' )(in the same block of code) outputs the sidebar’s widgets fine. Any ideas?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.
Another Gem of a tutorial.
Again, greatly appreciated.
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 ?
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 !. “
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.
The purpose of presetting is to have something there on first install. There’s no need to comment it out, no.
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.
Thanks for the heads up!
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.
I’ll second that comment.
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
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.
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
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.
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!
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
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.
Amazing, thanks!
It works.
Nout
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.”
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!
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.
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!
Thanks Chris, but can you give at specific fix, so us noobs can get it working again!?
Thanks again,
Michael
where is the donation page??
u had a donation page asking people to give you 100 bucks…
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.
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?
There is a fix described in the response above from Terrence
4 Trackbacks
[...] 原文:The WordPress Theme Sidebar Template [...]
[...] The Sidebar Template [...]
[...] The wordpress theme sidebar template [...]
[...] Editing the Sidebar Template [...]