Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
add comment

1 Answer 1

up vote 2 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">
  <?php
   $category = get_the_category();
   if (in_category($category[0]->slug) || is_category($category[0]->slug)){
        dynamic_sidebar( $category[0]->slug.'-widget-area' );
    };
   ?>
</ul>
</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
add comment

Your Answer

 
discard

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.