Codex

Widgets API

This article is marked as in need of editing. You can help Codex by editing it.

Contents

Widgets API

This page contains the technical documentation of the WordPress Widgets API (Application Programming Interface). The intended audience for this information includes WordPress theme authors, plug-in authors and anyone who would like to write a stand-alone widget. This document assumes a basic understanding of PHP scripting.

A widget is a PHP function that echoes string data to STDOUT when called. To turn such a PHP function into a Wordpress Widget it must be registered as such. This is done using a PHP callback (a Pseudo-Type in PHP documentation) that is registered by a wordpress widget API function.

The Wordpress widget API is located in wp-includes/widgets.php.

Function Reference

Sidebar Functions
Widget Functions

Define Sidebars

The functions listed below are used to add functioning sidebars to a theme.

Register Several Sidebars

register_sidebars( $count, $args );

Registers one or more sidebars to be used in the current theme. Many themes have only one sidebar. For this reason, the count parameter is optional and defaults to one.

The $args parameter will be passed to register_sidebar() and follows its format, with the exception of the name, which is treated with sprintf() to insert or append a unique number to each sidebar if count is plural.

For example, the following line will create sidebars name "Foobar 1" and "Foobar 2":

register_sidebars(2, array('name'=>'Foobar %d'));

Register Single Sidebar

register_sidebar( $args );

The optional $args parameter is an associative array that will be passed as a first argument to every active widget callback. (If a string is passed instead of an array, it will be passed through parse_str() to generate an associative array.) The basic use for these arguments is to pass theme-specific HTML tags to wrap the widget and its title. Here are the default values:

 'before_widget' => '<li id="%1$s" class="widget %2$s">',
 'after_widget' => "</li>n",
 'before_title' => '<h2 class="widgettitle">',
 'after_title' => "</h2>n"

There are times you might need to call this function instead of register_sidebars. An example of this would be when you want to give unique names to the sidebars, such as "Right Sidebar" and "Left Sidebar", or when they should be marked up differently. The names appear in the admin interface and are used as an index for saving sidebar arrangement. Please note: sidebar arrangements can be reused and overwritten when another theme is chosen that uses the same sidebar names.

The default before/after values are intended for themes that generate a sidebar marked up as a list with "h2" titles. This is the recommended convention for themes. Themes built using this structure can simply register sidebars without issues in regard to the before/after tags. If a theme cannot be marked up in this way, these tags must be specified when registering sidebars. It is recommended to copy the id and class attributes verbatim so that an internal sprintf call can work and CSS styles can be applied to individual widgets.

Display Sidebar on Theme

dynamic_sidebar( $sidebar );

This function calls each of the active widget callbacks in order, which prints the markup for the sidebar. If you have more than one sidebar, you should give this function the name or number of the sidebar you want to print. This function returns true on success, false on failure.

The return value should be used to determine whether to display a static sidebar. This ensures your theme will look good when the Widgets plug-in is not active. Along with a sanity test to prevent fatal errors, below is the recommended use of this function:

    <ul id="sidebar">
        <?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar() ) : ?>
            <li>{static sidebar item 1}</li>
            <li>{static sidebar item 2}</li>
        <?php endif; ?>
    </ul>

If your sidebars were registered by number, they should be retrieved by number. If they had names when you registered them, you will use their assigned names to retrieve them.

Developing Widgets

Developing Widgets on 2.8+

Widget development has become easier since version 2.8. To create a widget, you only need to extend the standard widget class and some of its functions.

That base class also contains information about the function that must be extended to get a working widget.

Default Usage

class My_Widget extends WP_Widget {
	function My_Widget() {
		// widget actual processes
	}

	function form($instance) {
		// outputs the options form on admin
	}

	function update($new_instance, $old_instance) {
		// processes widget options to be saved
	}

	function widget($args, $instance) {
		// outputs the content of the widget
	}

}
register_widget('My_Widget');

Example

This sample code creates a Widget named FooWidget that has a settings form to change the display title.

/**
 * FooWidget Class
 */
class FooWidget extends WP_Widget {
    /** constructor */
    function FooWidget() {
        parent::WP_Widget(false, $name = 'FooWidget');	
    }

    /** @see WP_Widget::widget */
    function widget($args, $instance) {		
        extract( $args );
        $title = apply_filters('widget_title', $instance['title']);
        ?>
              <?php echo $before_widget; ?>
                  <?php if ( $title )
                        echo $before_title . $title . $after_title; ?>
                  Hello, World!
              <?php echo $after_widget; ?>
        <?php
    }

    /** @see WP_Widget::update */
    function update($new_instance, $old_instance) {				
	$instance = $old_instance;
	$instance['title'] = strip_tags($new_instance['title']);
        return $instance;
    }

    /** @see WP_Widget::form */
    function form($instance) {				
        $title = esc_attr($instance['title']);
        ?>
            <p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('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 $title; ?>" /></label></p>
        <?php 
    }

} // class FooWidget

This sample widget can then be registered in the widgets_init hook:

// register FooWidget widget
add_action('widgets_init', create_function('', 'return register_widget("FooWidget");'));

That's all. You will automatically get a multi-widget. No special tweaks needed any longer for that.

More information is available in the version 2.8 information.

Developing Widgets before 2.8

The Google Search widget, which was included in the deprecated widget plugin, is well commented and can be used as a guide. Below are additional guidelines to follow:

  • Don’t execute any code while the plugin is being loaded. Using the plugins_loaded hook will help you avoid the risk fatal errors due to undefined functions.
  • Use register_sidebar_widget($name, $callback) to add your widget to the admin interface.
  • Follow this template:
      function widget_myuniquewidget($args) {
          extract($args);
      ?>
              <?php echo $before_widget; ?>
                  <?php echo $before_title
                      . 'My Unique Widget'
                      . $after_title; ?>
                  Hello, World!
              <?php echo $after_widget; ?>
      <?php
      }
      register_sidebar_widget('My Unique Widget',
          'widget_myuniquewidget');

Important: To use the above in a plugin, wrap it with:

function widget_myuniquewidget_register() {
  --the above goes here--
  register_sidebar_widget('My Unique Widget','widget_myuniquewidget');}
add_action('init', widget_myuniquewidget_register);
  • Don’t leave out $before_widget, $after_widget, $before_title, or $after_title. They are required for compatibility with various themes.
  • Name your widget and its functions carefully. Those strings will be used as HTML attributes and you don't want identical id's in a single HTML document.
  • Localization is done internally to preserve the HTML id attribute. If you want your widget name localized with a textdomain, pass array($name, $textdomain) instead of $name.
  • To accommodate multi-widgets (e.g. Text and RSS) you can also pass a replacement value with the name: array($name_as_sprintf_pattern, $textdomain, $replacement). See the source for additional information.
  • You may use the variables mentioned above in different ways, or neglect them in some circumstances. Some widgets may not need a title, for example. Some widgets will use the $before_widget and $after_widget several times, or as arguments to tell another template tag how to format its output.
  • Optionally, use the following syntax to add a configuration page to the admin. Your callback will be used within the main form, so you must not include any <form> tags or a form submit button.
      register_widget_control($name, $callback [, $width [, $height ]] );
  • Namespace your form elements so they don’t conflict with other widgets.
  • Each widget must have a unique name. You can replace an already-registered widget by registering another one with the same name, supplying your own callback.
  • Any extra arguments to register_sidebar_widget() or register_widget_control() will be passed to your callback. See the Text and RSS widgets for examples.
  • Any widget or control can be "unregistered" by passing an empty string to the registration function.
  • You are encouraged to read the source code to see how we've created the standard widgets using these functions.
  • Please test your widgets with several themes other than Classic and Default (they both use the ul/li/h2 markup).
  • Please audit the security of your widgets before distributing them.
  • If you would like your widget to be considered for use on WordPress.com, send a link (no attachments please) to widgets@wordpress.com for consideration.

What else can I do with Widgets?

Thanks for asking. Here are a few ideas:

  • Write a theme that includes a special widget to set it apart from the others.
  • Use a WordPress loop to show asides.
  • Register a replacement widget that buffers the original widget and transforms it somehow.
  • Remember that a "widget" is really just a name for a configurable code snippet. It can be invisible or it can be absolutely positioned horizontally or vertically.
  • Use the id and class attributes of any or all widgets in scripts to animate your sidebar.
  • Try using jQuery (included with WordPress) to make your widgets draggable or even collapsible.
  • Remember, the widget control API is available for your convenience. You can always set up your own admin page instead.
  • Support your users and get feedback so you can improve your widget. Put a link to your email or your site at the bottom of your widget control.
  • To have your widget(s) considered for use on WordPress.com, please send a link (no attachments please) to widgets@wordpress.com.

Widgets - Multiple Instances

Widgets can be coded for multiple instances or a single instance.

Resources