WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want display different content in sidebar for every category, but as I create new ones I have to create the area for it. How can I have widget areas for every category and also display them on theme accordingly?

share|improve this question
up vote 3 down vote accepted

Not a good thing if you have a lot of categories, so be careful!

First, add the following function in functions.php:

add_action( 'widgets_init', 'generate_widget_areas' );

function generate_widget_areas() {

//Do not create for uncategorized category
$terms = get_categories('exclude=1&hide_empty=0'); 

foreach ($terms as $term) {
   register_sidebar( array(
    'name' => 'Category '.$term->name,
    'id' => $term->slug.'-widget-area',
    'description' => 'Widget area for category and posts in '.$term->name,
    'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
    'after_widget' => '</li>',
    'before_title' => '<h3 class="widget-title">',
    'after_title' => '</h3>'    ) );

This is enough, now in Widgets you have a widget area for every category. Now you have to show the area for the category. I like to display the area for categories listings (categories posts listings) and the same area for posts using the category as well (single posts pages).

In sidebar.php, add:

<?php if (is_category() ||is_archive()||is_single()) : ?>
<div id="categories" class="widget-area" role="complementary">
<ul class="xoxo">
   $category = get_the_category();
   if (in_category($category[0]->slug) || is_category($category[0]->slug)){
        dynamic_sidebar( $category[0]->slug.'-widget-area' );
</div><!-- #categories .widget-area -->
<?php endif; ?>

That's all, I bet someone can came up with a better code, by now this does the trick.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.