How to Create Widget for Each Category in WordPress?

How to Create Widget for Each Category in WordPress?

Sometimes your client ask to have different sidebar for each of the categories pages on your wordpress site. Client may want show different section for different categories and I think requirement is quite obvious. To do this you have to use below action in function.php. It will straightway create widget area for every category on wordpress site.

add_action( 'widgets_init', 'category_sidebars' );

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, above code simply create widgets. But to call appropriate widgets per category we have to call specified widget. Here is the code you have to use in sidebar.php

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

I hope it will solve your problem.

Leave a Reply

Your email address will not be published. Required fields are marked *

Show Buttons
Hide Buttons
%d bloggers like this: