Creating Widgets for WordPress 2.8


Seeing how popular my How to Create WordPress Widgets post has been, I thought it was about time I wrote an updated guide to include creating widgets using the new WordPress 2.8 Widget API.

The API greatly simplifies the creation of widgets and all widgets using the API benefit from settings pages, multiple instances and more.

At the most simplistic level, a Widget now takes the form of a Class (object orientation) which contains 4 functions. The basic structure of a WordPress widget is shown below.

class Sample_Widget extends WP_Widget
{
  function Sample_Widget() { }
  function form($instance) { }
  function update($new_instance, $old_instance) { }
  function widget($args, $instance) { }
}
add_action( 'widgets_init', create_function('', 'return register_widget("Sample_Widget");') );

In this example we create a widget called “Sample_Widget” and tell PHP that it is going to extend (inherit from) the WP_Widget class. It is the WP_Widget class which makes your widget function, have settings and allow multiple instances so you don’t have to.

You will need to rename every occurrence of “Sample_Widget” with the name of your widget.

The first method, Sample_Widget() in the example, is the class constructor which contains the code that is run every time the widget is loaded – either when activated, used on a page, updated and so on.

The second method, form(), contains the settings page on the Widgets admin screen. This method is always called form and never changes. Within this function you add all the controls that will appear when the widget options are expanded. See below for an example.

The third method, update(), is called when the user click on “save” from the settings page on the widgets admin screen. This automatically handles saving to the database of options. You can use this function to validate information prior to being saved. See the example below for basic operation.

Finally the widget() function contains the code that will be rendered to the sidebar when the widget is added. This is what your visitors will see when viewing your page.

Let’s have a look at a very simple example “Hello World” widget.

Example

This example shows how to create a widget which outputs “hello world” to the sidebar. It also demonstrates adding a user configurable title setting to the widget in the admin panel, saving and retrieving user settings and displaying the widget.It shares the same structure as the basic example above, but has been expanded to include the entire plugin code. Simple copy and paste this into a text file called SampleWidget.php and upload it to your plugins folder. You can then activate and play around with it.

 
<?php
/*
Plugin Name: Sample_Widget
Plugin URI: http://azuliadesings.com/
Version: 1.0
Description: My Sample Widget Description
Author: Tim Trott
Author URI: http://azuliadesings.com/
*/

class Sample_Widget extends WP_Widget
{
  function Sample_Widget()
  {
    $widget_ops = array('classname' => 'Sample_Widget', 'description' => 'My Sample Widget Description');
    $this->WP_Widget('Sample_Widget', 'My Sample Widget', $widget_ops);
  }

  function form($instance)
  {
    $instance = wp_parse_args((array) $instance, array( 'title' => '' ));
    $title = $instance['title'];
?>
  <p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<?php
  }

  function update($new_instance, $old_instance)
  {
    $instance = $old_instance;
    $instance['title'] = $new_instance['title'];
    return $instance;
  }

  function widget($args, $instance)
  {
    extract($args, EXTR_SKIP);

    echo $before_widget;
    $title = empty($instance['title']) ? '' : apply_filters('widget_title', $instance['title']);

    if (!empty($title))
      echo $before_title . $title . $after_title;;

    // Do Your Widgety Stuff Here...
    echo "<h1>Hello World</h1>";

    echo $after_widget;
  }
}
add_action( 'widgets_init', create_function('', 'return register_widget("Sample_Widget");') );

?>

In the Sample_Widget function (technically called the constructor) I created some configuration options which will help WordPress (and the users of your widget) showing a friendly title and description.

The form method takes in the current settings as the $instance so you can use this to output the current settings to the user so they can update.

The update method does not do anything too complex, if you add another setting property add a line in here for it otherwise it won’t get updated.

Finally the widget method will generate the output for the widget. Notice the $args parameter, this is exactly the same as the $args parameter on the old style widgets. $instance contains the settings for this particular widget. If you need help on the $before_widget etc… please see the previous tutorial for explanations.

Creating Widgets for WordPressCreating Widgets for WordPress

I hope this quick guide helps you to migrate your old code or to create fantastic new widgets!

Copy from http://azuliadesigns.com/creating-widgets-wordpress-28/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s