The Dynamic Sidebar

March 18th, 2008

Having a dynamic sidebar is a great way to make your website more user-friendly! You can display extra content to enhance your pages or provide additional navigation links for sub-sections. Since the release of my new design, I've had a few people ask how I made my sidebar change on each page using Wordpress.

The Dynamic Sidebar

I am going to attempt to walk you through the entire process that I used to create the effect. But before I dive into that abyss (because it truly is one), I want to mention that this is an advanced way of manipulating code in Wordpress and is not recommended for beginners unless you do some additional research.

There is also a snippet of example code for a dynamic sidebar on the WP Codex, but it might be easier to understand here because you can build it along with me.

We will be utilizing Wordpress's Conditional Tags and Template Tags on our sidebar.php template page. This is the only template page in your theme folder that you will need to edit. It may get quite long code-wise (mine is about 200 lines), but have no fear, I will also show you how to organize it all as well. :)

For this walkthrough, I will be using my website (this one!) for most of the page structure and examples. At the end, I will provide you with a downloadable version of the advanced sidebar we will construct using the conditional tags. However, you are welcome to download it now to play with as we go through the steps.

Got it? Ready to go? Woot, let's get to it. I would advise you now to open up the "Tags" pages I linked above in new windows (or tabs) so you can easily reference them throughout this whole thing.

Basic Structure

The first thing to do is to create little placeholders in the sidebar for our content. Utilizing the conditional tags (of which I am going to assume you have looked over), and some PHP magic, we can write this like so:

<?php if (is_home()) { ?> Home content. <?php } ?>
<?php if (is_single()) { ?> Single post content. <?php } ?>
<?php if (is_archive()) { ?> Archive content. <?php } ?>
<?php if (is_search()) { ?> Search results content. <?php } ?>
<?php if (is_page()) { ?> All pages content. <?php } ?>
<?php if (is_page('about')) { ?> About content. <?php } ?>

The is_home() tag tells Wordpress that the content in between the { brackets } should only be displayed on the homepage. The is_page() tag declares the content inside to show only on a page. Please remember to keep <?php ?> wrapped around the opening and closing of each function.

Post or Page Slug

To specify which page to display it on (in this example the page is "about"), you will need to add either the page's ID, title or slug in between the parentheses, as displayed above. I am currently using the page slug, "about", because that seems easiest to me.

Read up on the other tags (archive, single, search, etc) to familiarize yourself with what type of page will display. You are free to play around with my website to see what content pops up on the sidebar while viewing different pages. Try browsing using my sitemap or type in a random search query in the box on the top-right. :)

You could honestly stop at the code above and just plug in what content you want for each specific page. But, for example, if you are wanting certain content to appear on the homepage and the archive pages but not on the search results page (or some similar structure), then please continue reading. :)

Advanced Structure

Here is where the code gets sticky. Let's say we want to tell Wordpress to display the phrase "I am a geek." on ONLY the homepage and archive pages. Keep in mind that the is_archive() tag applies to all types of archives (category, tag, date, etc).

<?php if ((is_home()) or (is_archive())) { ?> I am a geek. <?php } ?>  

Notice the extra parentheses surrounding the two functions and the OR statement between them. Double check the number of your parentheses because once you go beyond just one function they start to multiply like bunnies. :P Each opening parenthesis must have a closing partner at the end.

Because this can get complicated, I highly recommend you to use a program like Notepad++ for code editing. This program has a lovely feature which will highlight the opening/closing bracket or parenthesis when your cursor is next to it. Extremely handy. Also, I love how you can color your code (see picture at top of post).

Moving on then. So what if we ended up wanting to have our "I am a geek." phrase appear on the "About" page along with the home and archive pages? At this point, you simply need to add another OR statement to the end:

<?php if ((is_home()) or (is_archive()) or (is_page('about'))){ ?> I am a geek. <?php } ?>  

You can keep adding more conditional tags to this string if you like. It allows you to get extremely specific as to what pages you want content to appear on. Again, watch the number of your parentheses.

Specific Archives

Since the is_archive() function just generically represents all types of archives in Wordpress (category, tag, date, author, etc), you may want to narrow it down a bit and only display posts or content in certain ways for each archive.

For example, on every category archive page of my site I wanted a description of the category to appear on the sidebar at the top. You can see this effect on the Geeky category. To do this, you simply need to use the is_category() tag:

<?php  if (is_category()) { ?><?php echo category_description(); ?><?php } ?>

This is also the way I use to give my specific archive pages different certain looks. If you look at one of my tag archives versus a category archive, you should notice a few differences between how the posts are displayed.

Post Information

If you are familiar with Wordpress then you have seen how the system adds information about each individual post on its single post page. Take this post, for example, and note that I have moved the info from its typical spot underneath the post to the top of the sidebar. This isn't possible by just moving code from single.php to sidebar.php. There is a trick you need to pull off first.

If you look at any page template for your WP theme that displays posts (index.php, single.php, etc) you will notice that there is always a specific one or two lines of code that appear usually at the top of the template:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

This code is called the Wordpress Loop and it is pretty much the meat and potatoes of how your blog displays. Without this loop, your entries would not show up! This also goes for any tags inside of the loop (the_title(), the_content(), etc), meaning they won't work either without being inside of the loop.

So if we want to take the post information out of the loop and into our dynamic sidebar, how do we do that without messing everything up? The only answer is to make a new loop! :) The great thing about Wordpress is that it allows you to have multiple loops to manipulate posts and info on a page.

This let's us take the loop code and add it to our sidebar along with the post information we want to display:

<?php if (is_single()) { if (have_posts()) : while (have_posts()) : the_post(); ?>
<p>Written at <?php the_time('g:ia'); ?> in the <?php the_category(', '); ?> category.
Tagged by <?php the_tags('', ', ', ''); ?>.</p>
<?php endwhile; ?><?php endif; ?><?php } ?>

Note that I also added an additional conditional tag, is_single(), to the mix, making sure that the loop with the post information will ONLY appear on a single post page. It will mess up the rest of your blog otherwise!

Working With Subpages

If you've read my previous article, Dynamic Subnavigation, then you should familiar with the code required to identify a subpage and parent page (if not, go read it now!). With this technique, we're going to learn how to manipulate additional sidebar content beyond just the subnavigation.

The example I'm going to use here is my extras section, which I'm currently giving a facelift. One of the fun features I offer my visitors is a plugboard, which is a subpage of "Extras", using Bubs' sweet button board plugin for WP.

The plugin allows for you to have a "mini plugboard" you can add anywhere on your site to showcase the latest buttons added. I want to add this to the sidebar and have it appear whenever someone views the "Extras" section and any subpage except for the plugboard page itself. Here is how this is accomplished:

<?php if ((is_page('extras') or $post->post_parent==72) and (!is_page('plugboard'))) { ?>
<ul><?php bbb_include(6, "<li>", "</li>"); ?></ul>
<?php } ?>

This statement means: "if the page is extras or the parent is (equal to, ==) extras and not (!) the plugboard page". Note the bold text additions and that "72" represents the page/post ID of my "extras" page.

The == and ! are logical operators, used to tie together different statements in PHP. I won't heavily go into explaining all that but check the link for more info. Make sure to keep in mind what at least those two operators used above mean. The and and or are also logical operators, but those are easier to remember. :)

Final Tips

I cannot stress enough the importance of keeping track of your parentheses! Many a time I have typed out some PHP, uploaded it and was presented with a big ol' error. That's why I still recommend using Notepad++ to highlight them. That program will also number the lines of code in the file so if you do happen to get an error you can quickly jump to the line number it gives you to correct whatever is wrong.

Consult the Conditional Tags and Template Tags pages as often as possible! You can pretty much use any conditional tag with any of the examples I've given you here to display your content. It's that easy to mold. :)

Don't forget to take it slow with this stuff. It can get complicated really fast if you are wanting to have lots of content on your sidebar, switching it up all the time. Start small, like maybe with just subnavigation and then build it up from there.

Download Example

I have combined all of the above code in a simple file for you to download and play with. It is named sidebar.php so you can just add in your content and tweak it to your heart's content before dropping it right into your theme folder.

Download (1.06kb)

If you have any questions or need help with something specific I can try my best. :) Please post your code in the comments below and I will take a look. Hope this article helps other Wordpress enthusiasts! :D

This article is part of my Dynamic Walkthroughs series for tweaking Wordpress.

Other Resources:

Comments

Would you like to add one?

Ann Mar 18, 2008

AHHHHH! I’m just coming to the end of figuring out conditional tags for my new layout (couldn’t you have written this last week?!), this is amazing, thank you! Notepad++ sounds exactly like what I need with my tendancy to miss off brackets…
Anyway, thanks very much for this, it’s really helpful!

Melissa Mar 18, 2008

LOL! No problem! And I actually had written most of it a couple weeks ago, I just slacked on finishing. :P But I hope it helps you tie up any loose ends! :D

Marieke Mar 18, 2008

Ohw… thank you so much ^^. The sidebar I have right now uses div-styles at the moment, so I guess I will to covert this to h1,h2,h3 etc. first? And then I can try to do something with these things? It all seems a bit difficult but maybe with some help (… okay, lots of help :P) I might be able to do it. Thanks anyway for sharing this!

Melissa Mar 18, 2008

You shouldn’t have to convert anything! :) You can just move what you want to show between the closing and ending brackets { } in the PHP code.

I know you’ve just switched over to WP recently, Marieke, so don’t rush into anything too quickly! All this stuff can get pretty complicated and confusing pretty fast. But we are here to help you! :D

Vira Mar 18, 2008

Yay! I was just about to go looking for a tutorial for this exact thing! I’m glad that I can use your tutorial. That way I can ask you questions if I’m lost! lol I will have to come back to it later though. :(

Jenny Mar 18, 2008

Ok well I learned ONE new thing. xD Thanks for this.

Melissa Mar 18, 2008

That way I can ask you questions if I’m lost!

You are always welcome to! :D

Ok well I learned ONE new thing.

Only one? XD

Hev Mar 18, 2008

Oh my, Melissa. Thank you so very much. I have been waiting on this. I think :) I can’t wait to start fiddling with this I am getting excited about new templates for my sites. Thanks again. I don’t know what I would do without your resources or your help.

Barbilee Mar 19, 2008

OMG thats a wonderful tut on this when i redo my skin i try this *crosses fingers that this dummy can get it* …… thanks so much

Melissa Mar 20, 2008

You all are quite welcome. :)

Ann Mar 20, 2008

Hmm, I see you use “or” instead of “array”, like the conditional tag page on Wordpress suggests. Why is that exactly (’cause atm for some reason “array” won’t work for me, but it does save a bit of typing…)

Melissa Mar 20, 2008

The reason why array doesn’t work for you yet is because it is a Wordpress 2.5 feature. I may modify this walkthrough once it’s released and I can play around with it more.

Ann Mar 20, 2008

Ugh, these tricks wordpress plays.
This also does the same thing as the “or” though, right, just without the extra ()?

<?php if (is_home() || is_single()) { ?>

Vera Mar 20, 2008

That’s how I did my changing footer (I have that info my footer)… with the difference that I used a switch statement and the pages which make use of this are the ones not powered by wordpress :P

Melissa Mar 20, 2008

This also does the same thing as the “or” though, right, just without the extra ()?

You can use || but you need the extra parentheses. :) You can use any other logical operators (to my knowledge) to connect statements but I didn’t go over them to keep things simple.

Sarah Mar 21, 2008

This is a wonderful and useful tutorial. My method was getting very complicated so I have changed to this method. Thanks so much for sharing this with us, Melissa. :D

Melissa Mar 21, 2008

You’re welcome, Sarah! :D

Sarah Mar 21, 2008

Ick, just realised on the actual child pages the navigation doesn’t appear. Do I need to make extra tags for them? I did make tags for their parent pages.

Sarah Mar 21, 2008

Ah, sorry. Figured it out! Silly me. :D

Melissa Mar 21, 2008

It’s always more fun to figure things out yourself, isn’t it? XD

CARLY Apr 18, 2008

Thank you - very handy! I know I’ve used this tutorial once before, but I’ll be reaquinting myself today, and using it again!!

Arwen Apr 20, 2008

Okay, how would I do this:

I want a certain sidebar on all my pages EXCEPT for the single page, where I would have a different sidebar. Would I have to copy the content for each one, or could I do something like if() else()?

Thanks. :D

Melissa Apr 20, 2008

You could definitely use the conditional statements for that! :) The particular way to do it would be under the “Working with Subpages” section in this walkthrough, but this is how you would achieve it for your particular need:

<php if (!is_single()) { ?>

Content to appear if NOT single page.

<?php } else { ?>

Content to appear if IS single page.

<?php } ?>

The exclamation point added to the first statement means “not this”, generally speaking. I hope that helps!

Jessica Apr 27, 2008

I know I am missing this somewhere…. and instead of emailing you & all & not letting my idiotcity(sp) show… how do I stop the showing of the child’s child page. Like domain-reviews-review by… I want the review by not to show. Purty please show me the light.

Melissa May 02, 2008

Jessica, I’ve finally answered your question on my Dynamic Subnavigation walkthrough! XD It is under the “subpages of subpages” section.

I’ll email you to make sure you get your answer. :)

Jenny Jun 22, 2008

I use this in all my templates. It’s pretty handy if you ask me. :D

Clem Jun 29, 2008

This may just be me being stupid, but I’m having a bit of an issue. This works perfectly for sections, but in sub-sections, the sidebar doesn’t show. So, for instance, the sidebar shows up in About, but in About>Fanlistings, it doesn’t. Is there any way I can fix this?

Thanks so much for this awesome tutorial, btw!

Melissa Jun 29, 2008

I use this in all my templates. It’s pretty handy if you ask me. :D

Thank you, Jenny! :D Glad it helped.

…in sub-sections, the sidebar doesn’t show.

You’re not being stupid, don’t worry, this stuff can get confusing pretty fast. :) You’ll have to add some additional code to the PHP statement for the content you want to display. It’s explained more under the “Working with Subpages” heading towards the end of my tutorial.

So the code will look something like this:

<?php if (is_page(’extras’) or $post->post_parent==72) { ?>

Replace “extras” with the parent page you need and “72″ with the parent page’s ID. It’s also explained a bit in my other article: Dynamic Subnavigation.

I hope that helped! :D

Post a Comment

Your response may be added to a moderation queue if you have never commented before or your comment contains more than one link. If it has not appeared after a day, please contact me so I can check if it was marked as spam. Thank you! :)

Please quote people and converted code with <blockquote>. Allowed formatting includes: <strong>, <em>, <strike>, and <abbr>. You may use links that are friendly ones. :)

XD :nod: >_> :( ^_^ :P :X :goodie: :wah: :D :/ :dance: O_o 8| :| -_-; :no: XO X( :) :O :$ :cheer: :B ^^; :ohyeah: X_X ;) :T :heart:

Currently you have JavaScript disabled. In order to post comments, please make sure JavaScript and Cookies are enabled, and reload the page.