Feb 25, 2010

Add widget to page instead of sidebar in wordpress

Generally, it is required to add widgets (different from sidebar widgets) in specific page to simplify jobs. Suppose you have to show RSS feeds in specific wordpress page then it is better to add the RSS widget in the page to make life easier. Widget is placed only in sidebar. Can sidebar be customized as per custom layout?

The answer is YES.

You can create sidebars as per your requirement, place them in the page where you want and add different widgets in different sidebar.

Let us take simple example. Suppose you have to create custom page where widgets can be added then see following steps:

Step1: Register a new sidebar

For this, Open function.php in your active theme. If it calls register_sidebar function for existing sidebar then call it again to create new sidebar for the page.

Example:

For Single Sidebar template:

Initially it was

<?php if ( function_exists('register_sidebar') )

register_sidebar(array(

'before_widget' => '<div>',

'after_widget' => '</div>',

'before_title' => '<div>',

'after_title' => '</div>',

));

?>

Then I added register_sidebar function again for new sidebar.

Now it looks:

<?php if ( function_exists('register_sidebar') )

register_sidebar(array(

'before_widget' => '<div>',

'after_widget' => '</div>',

'before_title' => '<div>',

'after_title' => '</div>',

));

register_sidebar(array(

'before_widget' => '',

'after_widget' => '',

'before_title' => '',

'after_title' => '',

));

?>

In Other themes, I see the sidebar is registered in following way

<?php

if ( function_exists('register_sidebars') )

register_sidebars(2);

?>

Then increase the number for new widget bar:

<?php

if ( function_exists('register_sidebars') )

register_sidebars(3);

?>

Step 2: Create Custom Page Template (say WidgetPage.php)

<?php

/* Template Name: Widget Page

*/ ?>

<?php get_header(); ?>

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar(2) ) : endif; ?>

<?php get_footer(); ?>

Note 1: You need to give index of new sidebar. Suppose your theme has already 3 sidebar and you have registered for new sidebar then put dynamic_sidebar(4) instead of dynamic_sidebar(2).

Note 2: you can put anywhere the sidebar in layout. For example, If you have to put in table tag then

<table width="100%">

<tr>

<td>

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar(3) ) : endif; ?>

</td></tr>

</table>

Note 3: You can create multiple sidebars and call in same manner by changing index.

Step 3: Create Page based on this template:

Login to wordpress admin > Pages > Add New

Select “Widget Page” Template in attributes area and publish it.

wordpress template

Step 4: Add widgets:

Go to Appearance > Widgets > Expand newly created sidebar

Drag widgets to the sidebar, fill options and save it.

Open the page in browser and enjoy it.