Enabling Widgets

The functions.php file was added to the theme hierarchy in order to support the widget feature in WordPress 1.5. For each widget area you want in your theme, you need to register an array telling WordPress what the area should be called and what code should be displayed before and after the widget block and title.

Let's look at an example. The code in Listing 6-31 defines two widget areas. The results are shown in Figure 6-16.

Listing 6-31. Defining two widget areas function my_widgets_init() {

register_sidebar( array(

'name' => 'First Widget Area', 'id' => 'first-widget-area',

'before_widget' => '<li id="%1$s" class="widget-container %2$s">',

'before_title' => '<h3 class="widget-title">',

register_sidebar( array(

'name' => 'Second Widget Area', 'id' => 'second-widget',

'before_widget' => '<li id="%1$s" class="widget-container %2$s">',

'before_title' => '<h3 class="widget-title">',

// Add the widget areas add_action( 'init', 'my_widgets_init' );

Figure 6-16. The widgets defined by Listing 6-31

The classes and IDs in the widget code follow the PHP sprintf() syntax and allow each widget to have a unique ID and a class based on the widget type. For example, a text widget placed third in a widget area, after two other widgets, would open with the list item tag shown in Listing 6-32.

Listing 6-32. A text widget generated by Listing 6-30

<li id="text-3" class="widget-container widget_text"> <h3 class="widgettitle">This is a widget</h3> <div class="textwidget">

You can define as many widget areas as you like. Don't forget to make a place for your widgets in your sidebar.php file (or elsewhere in your theme), as described previously in the Sidebar section of this chapter.

0 0

Post a comment