Examining the Calendar Widget

Before I go into the details of custom widgets, let's take a look at the code for one of the simplest built-in widgets, the calendar (Figure 8-1). The code (from wp-includes/default-widgets.php) is given in Listing 8-1. Things you would change in your own widget are in bold.

Figure 8-1. The calendar widget in the widget manager area and the Twenty Ten theme

Listing8-1. The built-in calendar widget class WP_Widget_Calendar extends WP_Widget {

function WP_Widget_Calendar() {

// define widget title and description $widget_ops = array('classname' => 'widget_calendar',

'description' => _( 'A calendar of your blog’s posts') );

// register the widget

$this->WP_Widget('calendar', _('Calendar'), $widget_ops);

// display the widget in the theme function widget( $args, $instance ) { extract($args);

// apply filters to the given title, or print non-breaking space if empty $title = apply_filters('widget_title', empty($instance['title']) ?

' ' : $instance['title'], $instance, $this->id_base); // before/after code for widget and title were defined in functions.php echo $before_widget; if ( $title )

echo $before_title . $title . $after_title; // print the inner widget, the part that makes this widget unique echo '<div id="calendar_wrap">'; get_calendar(); echo '</div>'; echo $after_widget;

// update the widget when new options have been entered function update( $new_instance, $old_instance ) { $instance = $old_instance; // replace old with new

$instance['title'] = strip_tags($new_instance['title']); return $instance;

// print the widget option form on the widget management screen function form( $instance ) {

// combine provided fields with defaults

$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) ); $title = strip_tags($instance['title']); // print the form fields

<p><label for="<?php echo $this->get_field_id('title'); ?>">

<?php _e('Title:'); ?></label> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></p> <?php

Look how little you have to change! Now, I did say that this is one of the simplest widgets. Your widgets might have more options, and therefore a longer form and more fields to update. Still, this is going to be pretty easy, right?

I'll go through each piece of this widget, starting with the form and working backwards.

The Options Form

The form function defines what will appear in the widget manager under Appearance ^ Widgets. In the case of the calendar widget, there are no options other than the title, so the form shown in Listing 8-1 was unchanged. In your own widgets, you'll probably have an option or two, and you'll need to create a few more form fields. Let's review the form function by itself (Listing 8-2).

Listing 8-2. The form function

// print the widget option form on the widget management screen function form( $instance ) {

// combine provided fields with defaults

$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) ); $title = strip_tags($instance['title']); // print the form fields

<p><label for="<?php echo $this->get_field_id('title'); ?>"> <?php _e('Title:'); ?></label>

<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></p>

First, let's think about what this widget will display in the theme. The get_calendar() tag is pretty simple. It takes just one possible argument, the format of the days' names in the table heading. You don't need the argument here; the tag respects the time and date settings you chose in your General Settings screen. The tag, and thus the widget, simply prints a calendar, as shown in Figure 8-1. Therefore, you don't need any widget options other than the title of the widget itself. Were you generating a more complicated bit of code, you would need more options, as you'll see in the Random Posts from Category widget later in this chapter (Listing 8-7), and you would add those form fields here in the form function.

In the first line of the form function, you parse the arguments passed in the $instance variable and merge it with a second array containing the default values for your options. Then, before you display the title on the widget manager screen, you need to strip HTML tags. Widget titles are strictly defined; you saw this back in Chapter 7 when you defined the widget areas in functions.php. You need to keep stray HTML tags from interfering with the widget output, not to mention widget manager itself.

Now it's time to display the form fields. There's no need for a <form> tag; that will be taken care of for you. You just need to wrap the title in a <label> tag and provide an input field for each option—in this case, just the title itself.

To convert the stored value of a widget option into attribute-friendly strings, pass the name of the option to the get_field_id() and get_field_name() functions. For the value itself, use the $title variable again, this time passed through the esc_attr function.

And you're done with the form! The submit button will be added automatically.

The Update Function

The first thing to do in any widget update function is to save the old values, in case any of them didn't change. Then, go through each of the fields from your form, do any required processing on them, and save them to the new form instance.

In this case, the only thing you need to do with your widget title is, once again, strip any HTML tags. Listing 8-3 shows the isolated update function.

Listing 8-3. The update function

// update the widget when new options have been entered function update( $new_instance, $old_instance ) { $instance = $old_instance; // replace old with new

$instance['title'] = strip_tags($new_instance['title']); return $instance;

The Widget Output

Listing 8-4 shows the isolated widget output function.

Listing 8-4. The widget function

// display the widget in the theme function widget( $args, $instance ) { extract($args);

// apply filters to the given title, or print non-breaking space if empty $title = apply_filters('widget_title', empty($instance['title']) ? '&nbsp;' : $instance['title'], $instance, $this->id_base);

// before/after code for widget and title were defined in functions.php echo $before_widget; if ( $title )

echo $before_title . $title . $after_title; // print the inner widget, the part that makes this widget unique echo '<div id="calendar_wrap">'; get_calendar(); echo '</div>'; echo $after_widget;

The $args variable passed to the widget function is an array of all the fields in the form. To make them easier to work with, the first line extracts them into separate variables.

The next line is a bit complicated. It's an if/else statement using the ternary operator syntax. If you're not familiar with the ternary operator, it can be confusing to read. Unpacked, this line would look more like Listing 8-5.

Listing 8-5. A less compact way of processing the widget title

// First, you'll provide a non-breaking space if the title field was left empty. if (empty($instance['title'])) $title = '&nbsp;';

else

$title = $instance['title']; // Then, you need to apply filters, in case another plugin needs to alter widget titles $title = apply_filters('widget_title', $title, $instance, $this->id_base);

First, you provide a non-breaking space if the title field was left empty. Then, by calling apply_filters(), you allow plugins to modify the widget titles.

Once you have the title, you need to kick off the widget with $before_widget. Then you print the title using $before_title and $after_title. Recall that you defined all the before and after options back in Chapter 7 when you set up the widget areas in functions.php.

Now it's time to print the heart of the widget. In this case, you use just one template tag, get_calendar(), surrounded by a <div> tag (which might be useful for styling the widget). As you'll see later in this chapter, you could do something much more complicated here.

Once you're finished with the widget output, you print $after_widget, and you're done.

Setting up the Widget

Finally, the setup function is shown by itself in Listing 8-6.

Listing 8-6. The setup function function WP_Widget_Calendar() {

// define widget title and description $widget_ops = array('classname' => 'widget_calendar',

'description' => _( 'A calendar of your blog&#8217;s posts') );

// register the widget

$this->WP_Widget('calendar', _('Calendar'), $widget_ops);

The name of the first function in the class should match your widget name. This function provides the information about the widget WordPress needs to display on the widget manager screen.

You could accomplish all this in one line, but for readability, you'll create an array of the widget's properties (class name and description). Then you just need to initalize the widget with an internal name (calendar), a label (Calendar), and the array of properties.

■ Note: the description and label are shown wrapped in the __() function (that's two underscores and nothing else). As you will see in the next chapter, this function is used to translate the given strings into the user's chosen language.

0 0

Post a comment