Writing a WordPress Widget

Summary: How to write a quick and dirty WordPress widget to add social network links to your template.

Widgets are one of the coolest features in WordPress – they let you add all sorts of functionality to it. In this post, we’re going to look at how to take some stuff and stick it into a widget. The widget we’ll build is very trivial, but it should illustrate the point well enough. This widget will add links to allow our readers to share our posts on a social network – Facebook or Twitter. We’re looking to generate this kind of link:

   1: <a href="http://twitter.com/home?status=@karl_agius Reading Hello world! at http://localhost/blog/?p=1" class="twitter" title="Spread the word on Twitter!">Spread the word on Twitter!</a>
   2: <a href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Flocalhost%2Fblog%2F%3Fp%3D1" class="facebook" title="Share on Facebook">Share on Facebook</a></li>

We’ll also look at how to add a configuration page to the plugin so we can change settings without messing about in the code.

We are not going to look at how to style it and make it look neat, mainly because my design skills would make that a total and abject waste of time and brain cells. We’ll just pretend it looks nice and focus on the code instead.

The widget will be called Sociopath, because I couldn’t think of a name that makes any sense.

For the terminally impatient, the finished plugin can be downloaded here.

A widget is a plugin

Widgets are essentially plugins with a bit of added oomph. Since this post focuses on the bits that make widgets widgety, I’m going to skip over the raw plugin stuff here – if you’re interested in that, you can find more about it in the post about the FLIRt plugin.

Also, remember that widgets need a sidebar: if your theme doesn’t support one, read the codex article about widgetizing your theme.

Making a widget show up in the widgets page

To see a widget in the sidebar, you must first add it to one in the Widgets screen. To tell WordPress that our plugin contains a widget that needs to be displayed in this screen, we have to register it using the register_sidebar_widget function. We will do this in the ‘plugins_loaded’ action, which is when WordPress loads the list of active plugins:

   1: function sociopath_loaded()
   2: {
   3:     register_sidebar_widget('Sociopath', 'sociopath_widget');
   4: }
   5:
   6: add_action('plugins_loaded','sociopath_loaded');

As you can see above, register_sidebar_widget takes four arguments. The first is the widget id; the second is the display name, while the third is the callback that will be used to render the widget in the sidebar. The final parameter is a dictionary of widget options; in this case, we have a description, which adds some text to the widget in the administration screen:

The widget can now be selected and added to a sidebar.

select widgets

Rendering the widget

Rendering the widget is a no-brainer; we’ve already specified that the widget will be rendered with the sociopath_widget callback above, so that’s it. When we add the widget, it already knows where to go to get rendered.

To make sure your widget works well with themes, make sure you expand and echo $before_widget and $after_widget; their names are fairly self-explanatory:

   1: function sociopath_widget($args)
   2: {
   3:     extract($args);
   4:     echo $before_widget;
   5:     echo $before_title . $after_title;
   6:
   7:     sociopath_show_links();
   8:     echo $after_widget;
   9: }

Note that I have moved the actual rendering of the content into a separate method; this allows us to use the same code outside of the sidebar.

Giving the widget an options page

edit-widget

Widgets and plugins can both have a number of configurable options. Making our users mess with configuration files is, of course, an option, but that’s not especially clean. Luckily enough, the WordPress API provides a hook to allow you to add a set of configuration options to the Widget screen. To add a configuration form like the one in the screenshot, we have to create a function and register it using the register_widget_control function when we load the plugin:

register_widget_control('Sociopath', 'sociopath_widget_config');

The first parameter is the class name, which must be the same as that we used to register the widget. The second parameter is the function that WordPress will call when the user clicks the “edit” link in the widgets screen. This is the function that generates the configuration UI for us.

Unlike standalone configuration pages, widget control forms like this do not use their own HTML form. They only define their fields, other UI elements, and any behaviour that should be executed when the “Save changes” button is clicked in the widget page. The page provides the form and the rest of the wiring.

Refer to the function sociopath_widget_config in sociopath.php for an example.

You can use any mechanism you prefer to save data for your widget. In the case of this particular plugin, I decided to use the WordPress options; all the information required by the widget was easy to store in this form. However, there is nothing to stop you from using a database table or, indeed, anything else.

Using the widget directly in the theme

Of course, not all themes support widgets, and even if they did, you can bet your last dollar that someone will want to use it somewhere that no widget was ever meant to be. Thankfully, this is not much of a hassle at all… provided you plan for it.

The content of a widget itself can be rendered anywhere, as long as its plugin has been loaded. you just need to call the rendering method anywhere in your theme.

Configuration is more of a problem. If the widget only provides configuration options through its widget control, then there will be problems configuring it – you’d have to add the widget temporarily, make any configuration changes, and remove it again. That’s a hassle, of course. What I did with Sociopath was, instead, to add in a configuration page. It’s very definitely overkill for such a small plugin, but hey! this is an example, and a pretty convoluted one at that.

Further reading

Widgetizing plugins

Codex article on Options Pages

One Reply to “Writing a WordPress Widget”

Comments are closed.