So I spent a few days in the rabbit hole looking for a way to generate custom sidebars for categories and single pages – and display those sidebars dynamically based on what page/category template was being called.. Thankfully; there are a few hooks that allow for finding the category, displaying the category name, and using variables in the dynamic_sidebar function … Registering them ain’t too tough either…
Cutting to the chase; this is the function to register the sidebars based on what categories (that have posts; and are not empty) are in the DB … Dump this in your functions file and look at the widgets section — you will see new sidebars based on categories that you have that have posts – and these sidebars will be named the category name … Feel free to edit the before and after variables to match your existing theme:
if(function_exists('register_sidebar')) {
foreach((array)(get_categories()) as $category) {
register_sidebar(array(
'name' => $category->cat_name,
'before_widget' => '<div id="%1$s">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>', ));
}
Then; your going to need to find out what category the post is in within the WordPress database and display the appropriate sidebar for that category. You can use whatever widgets you want in there — this code has been tested on the index; category.php and single.php .. Using this on the archive or any other page — your mileage may vary…
<?php
$category = get_the_category();
$string = $category[0]->cat_name;
dynamic_sidebar( $string );
?>
That’s about it — If you need custom sidebars for categories in WordPress; this post should do wonders for you … Just a little code seems to go a long way with WordPress
Also; I have no idea what happens when a post is in two categories — you could do a for each in the dynamic_sidebar code; but my little project had things only categorized once .. Cheers!