Creating A Simple Widget In Wordpress

13th November 2008 - 3 minutes read time

A widget is a little program that fits into the side menu of your site. These widgets can be moved around using the admin section of your Wordpress blog and there are quite a few to chose from with a default install.

To create a theme that supports widgets you can follow the instructions in the post creating a widget proof Wordpress theme.

You can create a widget in one of two places, either within your functions.php file of your template, or in a plugin. To get a widget to display you need to call a function called register_sidebar_widget(). This function takes two parameters, the name of the widget in the admin section, and a callback function that controls what the widget contains.

register_sidebar_widget(__('My Widget'), 'myWidgetFunction');

The callback function takes a single parameter called $args, which is used to pass in all of the parameters that are set in the register_sidebar() function call. The first thing you have to do is use the extract() function to convert the $args variable into separate variables. After this function you will have access to such variables as $before_widget, $after_widget, $before_title and $after_title.

The following is an example of a very simple widget callback function that produces a widget with a single bit of text.

function myWidgetFunction($args) {
 extract($args);
 echo $before_widget;
 echo $before_title . __('My Widget') . $after_title;
 echo '<ul><li>The contents of my widget go right here.</li></ul>';
 echo $after_widget;
}

Of course if you wanted the widget to do something more interesting, which is probably your intent, then you can replace this line of text with a loop, or function call or whatever you need.

When you visit the widgets page in the Design section of your blog admin you will now see a widget called My Widget, which you can add to the current widgets on your blog.

Finally, you might have noticed that there is no descriptive text for the widget in your admin section. To add this you have to use the wp_registered_widgets variable, which contains an array of the registered widgets. You need to reference your widget and set an option called description to set the description in your admin section.

$wp_registered_widgets[sanitize_title('My Widget')]['description'] = 'A description of your widget.';

This took me quite a while to track down, and doesn't seem to be in any of the Wordpress codex.

Add new comment

The content of this field is kept private and will not be shown publicly.