Create Widgetized Sidebars for Each Category in WordPress

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' => '',
				'before_title' => '

', 'after_title' => '

', ) ); } }

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.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie