Displaying Your WordPress Widget on the Site

The final stage of creating your widget is to display its output on the site. You do this by further editing the WP_Widget class.

This is the final part in a five part series which you'll need to follow to get this far:

What You'll Need

To follow this tutorial, you'll need:

Coding the Widget's Output

There are two parts to this: adding a function outside the widget which will identify the ancestor page to use, and editing the widget function inside the WP_Widget class.

Adding the Ancestor Function

This function is taken directly from my earlier tutorial to create a plugin for context-sensitive sidebar navigation.

Above your WP_Widget class, add the function to your plugin file:

You will then use this later on when defining a query to run in the widget.

Editing the Widget Function

Next you'll need to edit the empty widget function you created earlier, in your plugin file. Start by defining the variable based on the form's input:

Next, add your query and its output, editing the function so it reads like this:

This checks if we're on a page and then defines the arguments for the list_pages() function using the output of the previous function and the value of the $depth variable which is set by the widget's form.

Now save your widget and check your site. Your list should display wherever you've added the widget:

The Final Plugin

You now have a complete widget plugin!

To recap what you've covered in all five tutorials, here's what the plugin code should look like in full:

Summary

Creating a widget does involve a few steps. These are:

  • Registering your widget
  • Creating the class to hold the widget functions
  • Writing a construct function to construct your widget
  • Writing a form function for the form in the Widgets screen
  • Writing an update function so the widget can update from the form
  • Writing a widget function with the output.

Once you've done all these, you will have a working widget, which you can adapt however you want.

Tags:

Comments

Related Articles