One of the greatest features in WordPress is the ability to create multiple widgetized areas. There are tons of widgets available in the WP plugin directory so having the ability to customize different areas of your site is a must. Registering sidebars in your theme’s functions.php file is pretty straightforward, but wouldn’t it be a whole lot easier to automate your theme to create a unique widgetized sidebar for each of your category pages? It’s actually not as hard as your would think.

All you need to start things off, is to add the following to your functions.php file:

add_action( 'widgets_init', 'category_sidebars' );
 * Create widgetized sidebars for each category
 * This function is attached to the 'widgets_init' action hook.
 * @uses	register_sidebar()
 * @uses	get_categories()
 * @uses	get_cat_name()
function category_sidebars() {
	$categories = get_categories( array( 'hide_empty'=> 0 ) );

	foreach ( $categories as $category ) {
		if ( 0 == $category->parent )
			register_sidebar( array(
				'name' => $category->cat_name,
				'id' => $category->category_nicename . '-sidebar',
				'description' => 'This is the ' . $category->cat_name . ' widgetized area',
				'before_widget' => '<aside id="%1$s" class="widget %2$s">',
				'after_widget' => '</aside>',
				'before_title' => '<h3 class="widget-title">',
				'after_title' => '</h3>',
			) );

Now you have a function that will loop through your categories and create a new sidebar for each. With that in place, all that’s left is to add a couple of lines of code to your sidebar.php file in order to call the appropriate sidebar on your category pages:

$sidebar_id = ( is_category() ) ? sanitize_title( get_cat_name( get_query_var( 'cat' ) ) ) . '-sidebar' : 'sidebar';
dynamic_sidebar( $sidebar_id );

The above code will default to a sidebar with the ID ‘sidebar’ unless you are on a category page, then it will find the current category and display the category’s custom sidebar. This gives you the ability to control which widgets are displayed for each category, allowing you to have even more control over your site’s layout.

As a modification to show category widget in the individual category’s posts? (I.E. open the post of “Category A”, there should be a “Category A” Custom Menu on the “Category A” post. Or, open the post of child category of “Category A”, there should be a “Category A” Custom Menu on the post.)

Removing this line:

if ( 0 == $category->parent )

Will allow sub-categories to appear.

If you change the sidebar call conditional from this:

( is_category() )

To this:

( is_category() || in_category() )

You should now have those category sidebars appear on post within that category.