Coding and Registering Your WordPress Widget

This is the second part in a series showing you how to create your first WordPress widget. In the first part you learned about the Widgets API and the WP_Widget class. In this part you'll learn how to start the process of building your widget by creating the class to hold it and registering it.

In full, this series consists of five parts:

What You'll Need

To follow this series, you'll need:

  • A development installation of WordPress
  • A code editor

Setting Up the Plugin

First you need to set up your plugin. Create a new file in your wp-content/plugins directory. I've called mine tutsplus-list-subpages-widget.php.

Add the following to the file:

Obviously you'll want to change the author name and url, but this gives WordPress what it needs to display the plugin in the Plugins screen.

Save your plugin file.

Creating the Widget Class

The next step is to create a new class to extend the WP_Widget class.

Type this code into your plugin file:

Let's have a look at what that class consists of:

  • the __construct function will do what you expect - it will construct the function. Inside that function you'll define things like the ID of the widget, its title and description.
  • the form function will create the form in the Widgets screen that lets users customise or activate the widget.
  • the update function ensures that WordPress updates any settings that users input in the Widgets screen.
  • the widget function defines what's output by the widget on the front end of the site.

The last three of these have parameters which I'll explain in more detail in the relevant tutorials.

Registering the Widget

Your widget won't work unless you register it with WordPress. Below your class, add the function and hook to do this:

The register_widget() function is a WordPress function whose single parameter is the name of the class you just created.

You then hook your function to the widgets_init hook to ensure that it is picked up by WordPress.

Note: Your widget won't work yet and won't be displayed on the Widgets screen, so don't worry about activating the plugin just yet. You'll need to complete all the steps in this series for it to work.

Summary

You've now started the process of building your first WordPress widget. You've created a plugin for the widget, created a class to construct the widget and registered it.

In the next tutorial you'll learn how to construct the widget using your __construct function.

Tags:

Comments

Related Articles