Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
  1. Code
  2. WordPress

Building the Form for Your WordPress Widget

This post is part of a series called Introduction to Creating Your First WordPress Widget.
Constructing Your WordPress Widget
Displaying Your WordPress Widget on the Site

In the first three parts of this series, you've started creating your WordPress widget. In this part, I'll show you how to create the form for your widget and ensure that WordPress can update any settings on it.

This will mean writing two functions for your Tutsplus_List_Pages_Widget class: the form function and the update function.

To see all of the parts in this series, click the links:

What You'll Need

To follow this tutorial, you'll need:

  • A development installation of WordPress
  • A code editor
  • The code from the previous tutorial on constructing your widget.

Creating the Form

To create the form for your widget, you'll need to populate the form function that you've already added to your Tutsplus_List_Pages_Widget class.

Open your plugin file, find that function and edit it so it reads:

This adds the markup for the field, including one input field ($depth), which will be used to set how deep into the page hierarchy the list should go. The default is -1 which will display all levels.

Now save your plugin file. You'll find that the widget now has a form:

However if you type anything into it it won't save. So you need to allow the form to save what's input.

Allowing the Form to Update

To do this you need to work with the update function you created earlier on. Edit it so it reads:

This replaces the old value of the depth field ($old_instance) with the new value ($new_instance), and sanitises it using strip_tags. Now when you type into the field, it will save:


You now have a working form for your widget, which means everything is in place expect actually displaying your widget's output on the site. That's covered in the next tutorial.

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.