Make your dynamic sidebar more dynamic

Consider situation that you want to add different category description on every category page. This text must be easily edited via admin panel. What can you do?

Of course you will use dynamic sidebars to achieve this. So you register sidebar for every category in function.php file:

register_sidebar(array(
    name => 'Category index: Regular meetings',
    id => 'index-category-regular-meetings',
    description => 'Insert text about this category',
        )
);

Next you have to place the sidebar in your theme. Creating category page for every category (eg. category-name.php) just to add the sidebar in it, doesn’t seem to be a good idea. It’s better to have one category template, so you can put a lot of conditions just to add correct sidebar for correct category. Yep, this idea didn’t convince me ether. So what I did was much easier. I created variable that holds the category slug:

if (is_category()) {
  $cat = get_query_var('cat');
  $mycat = get_category($cat);
  $sidebar_name = 'index-category-' . $mycat->
  slug;
}

and than add to category.php dynamic sidebar using this variable as dynamic sidebar parameters, so finally it looked like this:

if (is_category()) {
  $cat = get_query_var('cat');
  $mycat = get_category($cat);
  $sidebar_name = 'index-category-' . $mycat->slug;
  dynamic_sidebar($sidebar_name);
}

It works for category but by defining variable in a different way you can use it to create more dynamic sidebars on pages, author page or your custom posts.

Dodaj komentarz