How To Create A WordPress Widget Plugin

In this tutorial, I’m going to explain you how to create your own widgets within a small plugin. This post will cover some extra points that you need to understand before creating the widget itself.

Step 1: How to create a plugin

First step is the creation of the plugin. And as you’ll see, it’s the not the hardest part. A plugin is extra code added to WordPress once you activate it. WordPress creates a loop through a folder to retrieve all available plugins and list them in the back office. To create your plugin, you’ll need an editor such as Dreamweaver (PC & Mac). I recommend you to create your plugin in a local install of WordPress, making it on a live server can cause some troubles if you make an error. So please, wait to test our plugin before placing on it your hosting.

Open now the folder wp-content/plugins. This where you are going to add your plugin. Create a new directory and call it “widget-plugin” (actually, this name can be whatever you want). Even if our plugin will only have one single file, it’s always better to use a folder for each plugin. In your directory, create a new file called “widget-plugin.php” (this name can be changed too), and open it. We are now about to add our first lines of code. The definition of a plugin under WordPress follows some rules that you can read here on the codex. Here is how WordPress defines a plugin:

1
2
3
4
5
6
7
8
9
10
11
<?php
/*
Plugin Name: Widget Plugin
Plugin URI: http://www.wpexplorer.com/
Description: A simple plugin that adds a simple widget
Version: 1.0
Author: WPExplorer
Author URI: http://www.wpexplorer.com/
License: GPL2
*/
?>

Save your file. By only adding code to our widget-plugin.php file we have created a plugin! Well, for now the plugin doesn’t do anything, but WordPress recognizes it. To make sure it’s the case, go your administration, and go under “Plugins” menu. If your plugin appears in the plugins list you’re good, otherwise make sure you followed my instructions and try again. You can now activate the plugin.

Step 2: Create the Widget

We are now going to create the widget itself. This widget will be a PHP class extending the core WordPress class WP_Widget. Basically, our widget will be defined this way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class wp_my_plugin extends WP_Widget {

    // constructor
    function wp_my_plugin() {
        /* ... */
    }

    // widget form creation
    function form($instance) { 
    /* ... */
    }

    // widget update
    function update($new_instance, $old_instance) {
        /* ... */
    }

    // widget display
    function widget($args, $instance) {
        /* ... */
    }
}

// register widget
add_action('widgets_init', create_function('', 'return register_widget("wp_my_plugin");'));

This code gives WordPress all the information the system needs to be able to use the widget:

    The constructor, to initiate the widget
    The form() function to create the widget form in the administration
    The update() function, to save widget data during edition
    And the widget() function to display the widget content on the front-end

1 – The constructor

The constructor is the part of code that defines the widget name, so we’ll only add one line of code to it, to make it look like this:

1
2
3
4
// constructor
    function wp_my_plugin() {
        parent::WP_Widget(false, $name = __('My Widget', 'wp_widget_plugin') );
    }

Please not the use of __(). This function is use by WordPress for translation. I really recommend you to always use these functions, to make your theme fully translatable.

2 – The form() function

This function is the one that creates the widget in the WordPress administration, this is were you’ll enter your data to be displayed on the the website. For now I’m just going to explain you ho to add text fields and text areas. We’ll see check-box, drop-down select and other methods in a next post. Here is what form’) must contain:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// widget form creation
function form($instance) {

// Check values
if( $instance) {
     $title = esc_attr($instance['title']);
     $text = esc_attr($instance['text']);
     $textarea = esc_textarea($instance['textarea']);
} else {
     $title = '';
     $text = '';
     $textarea = '';
}
?>

<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Widget Title', 'wp_widget_plugin'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
</p>

<p>
<label for="<?php echo $this->get_field_id('text'); ?>"><?php _e('Text:', 'wp_widget_plugin'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('text'); ?>" name="<?php echo $this->get_field_name('text'); ?>" type="text" value="<?php echo $text; ?>" />
</p>

<p>
<label for="<?php echo $this->get_field_id('textarea'); ?>"><?php _e('Textarea:', 'wp_widget_plugin'); ?></label>
<textarea class="widefat" id="<?php echo $this->get_field_id('textarea'); ?>" name="<?php echo $this->get_field_name('textarea'); ?>"><?php echo $textarea; ?></textarea>
</p>
<?php
}

This code is simply adding 3 fields to the widget. The first one is the widget title, the second a text field, and the last one is a textarea. Let’s see now how to save and update each field value with the update() function.

3 – The update() function

The update() function is really simple. As WordPress core developers added a really powerful widgets API, we only need to add this code to update each field:

1
2
3
4
5
6
7
8
9
// update widget
function update($new_instance, $old_instance) {
      $instance = $old_instance;
      // Fields
      $instance['title'] = strip_tags($new_instance['title']);
      $instance['text'] = strip_tags($new_instance['text']);
      $instance['textarea'] = strip_tags($new_instance['textarea']);
     return $instance;
}

And tada! the magic appears! You don’t need more code to save values, isn’t it awesome?

4 – The widget() function

The widget() function is the one that will output the content on the website. It’s what your visitors will see. This function can be customized to include CSS classes, and specific tags to match perfectly your theme display. Here is the code (please not that this code can be modified easily to fit your needs):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// display widget
function widget($args, $instance) {
   extract( $args );
   // these are the widget options
   $title = apply_filters('widget_title', $instance['title']);
   $text = $instance['text'];
   $textarea = $instance['textarea'];
   echo $before_widget;
   // Display the widget
   echo '<div class="widget-text wp_widget_plugin_box">';

   // Check if title is set
   if ( $title ) {
      echo $before_title . $title . $after_title;
   }

   // Check if text is set
   if( $text ) {
      echo '<p class="wp_widget_plugin_text">'.$text.'</p>';
   }
   // Check if textarea is set
   if( $textarea ) {
     echo '<p class="wp_widget_plugin_textarea">'.$textarea.'</p>';
   }
   echo '</div>';
   echo $after_widget;
}

This code isn’t complex, all you have to remember is to to check if a variable is set, if you don’t and if you want to print it, you’ll get an error message.