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.
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!
15 Responses
Hai . . . It was inspiring me! Thanks
Can’t imagine it’s that straight forward. Can’t wait to try this out. Thanks for sharing the recipe.
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.
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()’.
Can’t try right now (at work), but will it work with tags too?
@BabyGotMac: Didn’t tried yet, but I’m sure it does.
Oh, very cool. Much easier than the way I’ve been doing it!
This is useful if you have a blog talking about super uber multiple niches
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.
very, very useful!
You got yourself another RSS subscriber, awesome tips you got here
that great tutorial!
simple and effective!
nice!
Thank you sooo much. The line to make it work outside of the loop is a lifesaver!
Trackbacks: