How to build custom sidebar in WordPress

The below code need to add to theme’s functions.php.Id should be unique.You need to add your custom sidebar under widgets_init hook’s function.

add_action( 'widgets_init', 'custom_widget_init' );
function custom_widgets_init() {
    register_sidebar( array(
        'name' => __( 'Main Sidebar', 'theme-domain' ),
        'id' => 'sidebar-1',
        'description' => __( 'Widgets in this area will be shown on all posts and pages.', 'theme-domain' ),
        'before_widget' => '
<li id="%1$s" class="widget %2$s">',
	'after_widget'  => '</li>

	'before_title'  => '
<h2 class="widgettitle">',
	'after_title'   => '</h2>

    ) );

After adding code you easily see your custom sidebar in Appearance->Widgets. Now you can add wordpress default widgets or you own.

To fetch the contents of this sidebar to frontend.You need to add the code below.

<?php if ( is_active_sidebar( 'my-sidebar' ) ){ dynamic_sidebar('my-sidebar'); } ?>;


Leave a Reply