How to Write a Widget in WordPress 3

6 min read


WordPress 3 Complete

WordPress 3 Complete

Create your own complete website or blog from scratch with WordPress

  • Learn everything you need for creating your own feature-rich website or blog from scratch
  • Clear and practical explanations of all aspects of WordPress
  • In-depth coverage of installation, themes, plugins, and syndication
  • Explore WordPress as a fully functional content management system
  • Clear, easy-to-follow, concise; rich with examples and screenshots

Recent posts from a Category Widget

In this section, we will see how to write a widget that displays recent posts from a particular category in the sidebar. The user will be able to choose how many recent posts to show and whether or not to show an RSS feed link. It will look like the following screenshot:

WordPress 3 Complete

Let’s get started!

Naming the widget

Widgets, like plugins, need to have a unique name. Again, I suggest you search the Web for the name you want to use in order to be sure of its uniqueness. Because of the widget class, you don’t need to worry so much about uniqueness in your function and variable names, since the widget class unique-ifies them for you.

I’ve given this widget the filename ahs_postfromcat_widget.php.

As for the introduction, this comment code is the same as what you use for the plugin. For this widget, the introductory comment is this:

Plugin Name: April's List Posts Cat Widget
Plugin URI:
Description: Allows you to add a widget with some number of most recent posts from a particular category
Author: April Hodge Silver
Version: 1.0
Author URI:

Widget structure

When building a widget using the widget class, your widget needs to have the following structure:

class UNIQUE_WIDGET_NAME extends WP_Widget {

$widget_ops = array();
$control_ops = array();

function form ($instance) {
// prints the form on the widgets page

function update ($new_instance, $old_instance) {
// used when the user saves their widget options

function widget ($args,$instance) {
// used when the sidebar calls in the widget


// initiate the widget

// register the widget

Of course, we need an actual unique widget name. I’m going to use Posts_From_Category. Now, let’s flesh out this code one section at a time.

Widget initiation function

Let’s start with the widget initiation function. Blank, it looks like this:

function Posts_From_Category() {
$widget_ops = array();
$control_ops = array();

In this function, which has the same name as the class itself and is therefore the constructor, we initialize various things that the WP_Widget class is expecting. The first two variables, to which you can give any name you want, are just a handy way to set the two array variables expected by the third line of code.

Let’s take a look at these three lines of code:

  • The $widget_ops variable is where you can set the class name, which is given to the widget div itself, and the description, which is shown in the WP Admin on the widgets page.
  • The $control_ops variable is where you can set options for the control box in the WP Admin on the widget page, like the width and height of the widget and the ID prefix used for the names and IDs of the items inside.
  • When you call the parent class’ constructor, WP_Widget(), you’ll tell it the widget’s unique ID, the widget’s display title, and pass along the two arrays you created.

For this widget, my code now looks like this:

function Posts_From_Category() {
$widget_ops = array(
‘classname’ => ‘postsfromcat’,
‘description’ => ‘Allows you to display a list of
recent posts within a particular category.’);

$control_ops = array(
‘width’ => 250,
‘height’ => 250,
‘id_base’ => ‘postsfromcat-widget’);

$this->WP_Widget(‘postsfromcat-widget’, ‘Posts from a Category’, $widget_ops, $control_ops );

Widget form function

This function has to be named form(). You may not rename it if you want the widget class to know what it’s purpose is. You also need to have an argument in there, which I’m calling $instance, that the class also expects. This is where current widget settings are stored.

This function needs to have all of the functionalities to create the form that users will see when adding the widget to a sidebar. Let’s look at some abbreviated code and then explore what it’s doing:

function form ($instance) {

$defaults = array(‘numberposts’ => ‘5’,’catid’=>’1′,’title’=>”,’rss’=>”);
$instance = wp_parse_args( (array) $instance, $defaults ); ?>

<label for=”<?php echo $this->get_field_id(‘title’); ?>”>Title:</label>
<input type=”text” name=”<?php echo $this->get_field_name(‘title’) ?>” id=”<?php echo $this->get_field_id(‘title’) ?> ” value=”<?php echo $instance[‘title’] ?>” size=”20″> </p>

<label for=”<?php echo $this->get_field_id(‘catid’); ?>”>Category ID:</label>
<?php wp_dropdown_categories(‘hide_empty=0&hierarchical=1&id=’.$this->get_field_id(‘catid’).’&name=’.$this->get_field_name(‘catid’).’&selected=’.$instance[‘catid’]); ?>

<label for='<?php echo $this->get_field_id(‘numberposts’); ?>”>Number of posts:</label>
<select id=”<?php echo $this->get_field_id(‘numberposts’); ?>” name=”<?php echo $this->get_field_name(‘numberposts’); ?>”>
<?php for ($i=1;$i<=20;$i++) {
echo ‘<option value=”‘.$i.'”‘;
if ($i==$instance[‘numberposts’]) echo ‘ selected=”selected”‘;
echo ‘>’.$i.'</option>’;
} ?>

<input type=”checkbox” id=”<?php echo $this->get_field_id(‘rss’); ?>” name=”<?php echo $this->get_field_name(‘rss’); ?>” <?php if ($instance[‘rss’]) echo ‘checked=”checked”‘ ?> />
<label for=”<?php echo $this->get_field_id(‘rss’); ?>”>Show RSS feed link?</label>

First, I set some defaults, which in this case is just for the number of posts, which I think it would be nice to set to 5. You can set other defaults in this array as well.

Then you use a WordPress function named wp_parse_args(), which creates an $instance array that your form will use. What’s in it depends on what defaults you’ve set and what settings the user has already saved.

Then you create form fields. Note that for each form field, I make use of the built-in functions that will create unique names and IDs and input existing values.

  • $this->get-field_id creates a unique ID based on the widget instance (remember, you can create more than one instance of this widget).
  • $this->get_field_name() creates a unique name based on the widget instance.
  • The $instance array is where you will find the current values for the widget, whether they are defaults or user-saved data.

All the other code in there is just regular PHP and HTML. Note that if you give the user the ability to set a title, name that field “title”, WordPress will show it on the widget form when it’s minimized. The widget form this will create will look like this:

WordPress 3 Complete



Please enter your comment!
Please enter your name here