How to: create a dynamic sidebar

Do you ever wanted to be able to load different sidebars according to the current category? Here is a very simple recipe to learn how to easily create a dynamic sidebar.

Since WordPress 2.5, you can specify a sidebar name to be inclued:

<?php get_sidebar('name'); ?>

The above code will include the file named sidebar-name.php.

The following code will include a custom sidebar according to the category you are on:

<?php
    //to be able to use this outside the loop
    if ( have_posts() ) { the_post(); rewind_posts(); } 

    if ( in_category('1') ) {
        get_sidebar('cat1');
        //gets sidebar-cat1.php
    } elseif ( in_category('2') ) {
        get_sidebar('cat2');
        //gets sidebar-cat2.php
    } elseif ( in_category('3') ) {
        get_sidebar('cat3');
        //gets sidebar-cat3.php
    } elseif ( in_category('4') || in_category('5') || in_category('6') ) {
        get_sidebar('catRest');
        //gets sidebar-catRest.php
    } else {
        get_sidebar()
        //gets sidebar.php
    }
?>

Credits goes to Chris Cagle for this awesome recipe!

Related Posts

Related Posts

No related posts.

15 Responses

Nov 04 2008 10:55

Hai . . . It was inspiring me! Thanks :-)

Nov 04 2008 15:39

Can’t imagine it’s that straight forward. Can’t wait to try this out. Thanks for sharing the recipe.

Nov 04 2008 15:45

Glad you like it, guys! I have to agree that this recipe is very nice, thanks to Chris! I can’t wait to implement it on my blogs too.

Nov 04 2008 17:54

This can be used for any type of customization. I use a very similar format for my WP header. Allows me to customize things like the title, and have page specific CSS/JS. Look into things like ‘is_page_template(‘whatever.php’)’ and ‘is_404()’.

Nov 04 2008 21:59

Can’t try right now (at work), but will it work with tags too?

Nov 04 2008 23:16

@BabyGotMac: Didn’t tried yet, but I’m sure it does.

Nov 06 2008 21:26

Oh, very cool. Much easier than the way I’ve been doing it!

Nov 09 2008 22:49

This is useful if you have a blog talking about super uber multiple niches :)

Dec 25 2008 09:58

Thanks for the wonderful tip. I can now list the posts on the sidebar which are of a particular category say Blogging if a visitor is reading a post related to Blogging category.

Jan 10 2009 00:28

very, very useful!

You got yourself another RSS subscriber, awesome tips you got here :)

May 26 2009 09:23

that great tutorial!
simple and effective!

nice!

Dec 10 2009 19:49

Thank you sooo much. The line to make it work outside of the loop is a lifesaver!

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required