StackTips
 2 minutes

How to Register & Display Sidebars in WordPress

By Editorial @stacktips, On Sep 17, 2023 Wordpress 2.42K Views

Register sidebar

You can register sidebar by calling register_sidebar() method. Just provide a unique name to each sidebar (eg: “Right Sidebar”, “Left Sidebar”). These names are displayed in WordPress admin dashboard interface.

function wpb_widgets_init() {
register_sidebar( array(
		'name' => __( 'My Sidebar', 'wpb' ),
		'id' => 'my-custom-sidebar',
		'description' => __( 'The main sidebar appears on the right on each page except the front page template', 'wpb' ),
		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget' => '</aside>',
		'before_title' => '<h4 class="widget-title">',
		'after_title' => '</h4>',
	) );
}
add_action( 'widgets_init', 'wpb_widgets_init' );

Display sidebar

To display sidebar in your theme, you can use dynamic_sidebar() method by passing the sidebar id.

<?php if ( is_active_sidebar( 'my-custom-sidebar' ) ) : ?>
	<aside id="sidebar" class="sidebar right">
		<div id="sidebar" class="widget-area" role="complementary">
			<?php dynamic_sidebar( 'my-custom-sidebar' ); ?>
		</div>
	</aside>
<?php endif; ?>
stacktips avtar

Editorial

StackTips provides programming tutorials, how-to guides and code snippets on different programming languages.