Paulund
2012-02-12 #wordpress

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.

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>