How To Create A Widget Plugin For WordPress

WordPress is an amazing Content Management System with many great features such as widgets. 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. Here we go!
Step 1: How to create a plugin
I recently created a plugin called “Freelancer Widgets Bundle“, and some people asked me how to create such a plugin, so I decided to write this post. 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 Coda (Mac), or 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:
<?php
/*
Plugin Name: Name Of The Plugin
Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates
Description: A brief description of the Plugin.
Version: The Plugin's Version Number, e.g.: 1.0
Author: Name Of The Plugin Author
Author URI: http://URI_Of_The_Plugin_Author
License: A "Slug" license name e.g. GPL2
*/
?>
So, we have to modify this code to make it fit our needs:
<?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:
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:
// 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:
// 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:
// 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):
// 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.
Conclusion
As you saw, creating a WordPress widget isn’t complicated. We saw how to create simple inputs fields, and in my next post I’ll show you how to add more complex field types. But now i hope you enjoyed this first tutorial about widgets. I’ll be more than happy to hear from you in the comments section!
How To Create A Widget Plugin For WordPress Part 2
Don’t worry guys, the fun doesn’t stop here! Continue on to read How To Create A Widget Plugin For WordPress Part 2 →

Great tutorial AJ. – Thanks!
You’ll have to thank our awesome new Contributor “Rémi Corson” ;)
Very time article and I’m scratching my head how this plugin thing works. Thanks for writing a detailed article. Kudos.
Hi, if you need some help let us know!
Hi Aj, Thanks for share this post
very nice tutorial AJ congratulations
Thanks so much AJ and Remi. This is awesome. Keep up the great work. Love what you are doing :)
Thanks Mike!
very useful. tahnks…
Nice Tutorial… I’m going to use it Soon!
Regards.
David
You just simplified something that had my brain in knots. Thank you thank you thank you!
Hi, nice and easy tutorial.
All working fine for me except that carriage returns / line breaks in the textarea are not being passed through to the output on the public website.
The widget stores them fine but doesn’t output them
any ideas ?
can you share a bit your code pastebin or github gist?
The code for this is now shared on GitHub at https://github.com/clarkedesign/widgets/commit/bb5d69fc6561eef5ea2b3df43ba0369001694143
Awesome….. tanx
Really good tutorial, very clear and easy to modify. Cheers
Fantastic Tutorial ! Easy to follow and breaks down all the main components. This is how people need to communicate. I find it hard when people try to write tutorials and expect that certain knowledge is assumed. This is for no experience and in experienced people to become experienced. Well done!
Many thanks!
Really good, many thanks, I just made a widget for my plugin following your tutorial :D .
Only if you could explain the part of “apply_filters” since many noobs like me find it misterious. Also the extract($args).
Thanks for your effort sir!
Thanks! The apply_filters section is not very complicated but i couldn’t cover everything. I think that Pippin Williamson did an amazing tuto on his site a few months ago about that.