Introduction to Creating Your First WordPress Widget

For non-coders creating a WordPress site, widgets are great. They let you add menus, lists, feeds, text and much much more to widget areas which don't need to be limited to the sidebar. Many themes now feature widget areas in the footer, and the big theme frameworks often have widget areas in multiple locations such as the header and before and after the content.

In this five part series I'll take you through the steps required to create your first widget. The series will cover:

In this part I'll introduce widgets and the Widgets API.

Creating Widgets

To create a widget you extend the WP_Widget class, which includes a number of functions:

  • a function to process the widget
  • a function to display a form for the widget in the Widgets dashboard screen
  • a function enabling widget settings to be updated by users
  • a function to output the widget in any widget area it's added to.

In addition to this, you use the register_widget() function to register the widget you've created.

You can put pretty much anything you want inside a widget - static text, the output from a database query, a feed from another site and more. However it's important to remember that users will expect widgets to fit in a defined area on the page, so your widget's output shouldn't be too great.

WordPress comes with an array of widgets built in, so before you start coding your own, check that it isn't already in WordPress core.

In this series I'm going to create a widget from a plugin I developed for an earlier tutorial, on creating context-sensitive sidebar navigation. In that tutorial I developed a function which users with some knowledge of code could drop into their theme or attach to a hook, but it would be easier for users if they could add the navigation via a widget.

The Widgets API

The Widgets API includes the functions you'll need to create your widget. Let's take a look at each of them.

Firstly, there are four widget functions:

  • is_active_widget(): a conditional tag which checks whether an individual widget is active. Don't confuse it with is_active_sidebar(), which checks if widgets have been added to a specific widget area.
  • the_widget(): a template tag which displays a widget outside of widget areas.
  • register_widget(): the function to register a widget, which I'll be using later in this series.
  • unregister_widget(): unregisters a widget, meaning that it's no longer available for users via the Widgets screen.

There are also five internal functions:

To access these internal functions, you'll make use of the WP_Widget class. This is a constructor class, which you can extend to create additional widgets.

Summary

 This introductory tutorial has hopefully whetted your appetite for creating your own widgets. In the next tutorial I'll show you how to code your widget and register it.

Tags:

Comments

Related Articles