How To Register A Sidebar In WordPress

In this tutorial we will learn how you can register a new Sidebar for your WordPress blog. The best part about WordPress sidebars is that you can use them to add Widgets to your page.

688px-widget-panel

To register a sidebar you need to use the WordPress function register_sidebar().

WordPress Register Sidebar Function

<?php register_sidebar( $args ); ?>

The parameters that this accepts is a array of options.

<?php $args = array(
	'name'          => sprintf(__('Sidebar %d'), $i ),
	'id'            => 'sidebar-$i',
	'description'   => '',
	'before_widget' => '<li id="%1$s" class="widget %2$s">',
	'after_widget'  => '</li>',
	'before_title'  => '<h2 class="widgettitle">',
	'after_title'   => '</h2>' ); ?>

The options before_widget, after_widget, before_title and after_title all accept HTML tags which will be placed around the sidebar widgets.

Below is an example of creating a WordPress main sidebar add the following to your functions.php page.

if ( function_exists('register_sidebar') ) {
	register_sidebar(array(
		'name' => 'Main Sidebar',
		'before_widget' => '<div id="%1$s" class="widget %2$s clearfix">',
		'after_widget' => '</div>',
		'before_title' => '<h3 class="widget-title">',
		'after_title' => '</h3>',
	));
}

WordPress Dynamic Sidebar Function

Once you sidebar is registered you need to place this in your HTML by using the function dynamic_sidebar().

<?php dynamic_sidebar( $index ); ?>

The index parameter is the ID or name you give to your sidebar once it is registered.

Add the following to anywhere on your theme you would like the sidebar to appear.

<ul id="sidebar">
   <?php dynamic_sidebar( 'Right Sidebar' ); ?>
</ul>

Advertise here

Comment