In this tutorial I will show you how to add a widget to a theme template file.

Most WordPress themes have widget-ready sidebars, but you may want to display a widget somewhere else in your theme.  For example a home page with three columns of widgets.  If your theme does not have widget areas already set up or you need more then you need to create a new one in your theme files.

It is a fairly simple two step process:

 1. Register The Widget

To register multiple new widgets you need to open the functions.php file in your WordPress themes editor.

Add the following code to the functions file, making sure you place it in between php tags:

[codesyntax lang=”php”]

if ( function_exists('register_sidebars') ){
    register_sidebar(array(
        'name' => 'widget-1',
        'before_widget' => '<div id="widget1">',
        'after_widget' => '</div>',
        'before_title' => '',
        'after_title' => '',
));
register_sidebar(array(
        'name' => 'widget-2',
        'before_widget' => '<div id="widget2">',
        'after_widget' => '</div>',
        'before_title' => '',
        'after_title' => '',
));
}

[/codesyntax]

Give the widget area a name – e.g. widget-1 and in the before/after options you can place code which you wish to appear wrapped around either the widget itself or the title.

If you want to add additional widget just repeat the code starting at “register_sidebar(array(…” to “));)”.  Make sure to change the name of the widget.

For this example we have just wrapped it in a div tag with the id – widget1 and widget2.

More info on the register_sidebars function can be found @ http://codex.wordpress.org/Function_Reference/register_sidebars

 

2. Add The Widget Code To Your Theme

Now we can add the code that will call the widget to the correct location in our theme files. In your WordPress themes editor open the index.php file, or where ever you wish to add the new widget.

Find the location where you want to place the menu and add the following code to the theme file:

[codesyntax lang=”php”]

<?php /* Widgetized sidebar */
    if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('widget-1') ) : ?><?php endif; ?>

[/codesyntax]

Save the changes to the theme file.

If you now go to the widget area in WordPress admin you should see a new widget area in the right hand column with the name of your widget.

You can now add any widget you wish to this area.