Wednesday, March 11

How to generate and display widgets areas dynamically?

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

First, add the following function in functions.php:

    <?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.

SOURCCE: stackexchange

No comments:

Post a Comment