Creating Widgets for WordPress

Written by on Wednesday 28th April 2010 under WordPress

Wordpress widgets are Wordpres plugins that can be used to add functionality and content to your website pages, usually in a sidebar. This tutorial shows you how to create your own widgets for your own Wordpress theme, plugin or addon.

The WordPress API greatly simplifies the creation of WordPress widgets, and all widgets using the API benefit from settings pages, multiple instances and more.

At the most simplistic level, WordPress widgets now take the form of a Class (object orientation) which contains 4 functions. The basic structure of a WordPress widget is shown below.

  1. class Sample_Widget extends WP_Widget
  2. {
  3.   function Sample_Widget(){}
  4.   function form($instance){}
  5.   function update($new_instance,$old_instance){}
  6.   function widget($args,$instance){}
  7. }
  8. add_action('widgets_init',create_function('','return register_widget("Sample_Widget");'));

In this example we are going to create a WordPress widget called "Sample_Widget" and tell PHP that it is going to extend (inherit from) the WP_Widget class. It is the WP_Widget class which makes your widget function, have settings and allow multiple instances so you don't have to.

You will need to rename every occurrence of "Sample_Widget" with the name of your widget.

The first method, Sample_Widget() in the example, is the class constructor which contains the code that is run every time the widget is loaded - either when activated, used on a page, updated and so on.

The second method, form(), contains the settings page on the WordPress widgets administration screen (Appearance -> Widgets). This method is always called form and never changes. Within this function you add all the controls that will appear when the widget options are expanded. See below for an example.

The third method, update(), is called when the user click on "save" from the settings page on the widgets administration screen. This automatically handles saving to the database of options. You can use this function to validate information prior to being saved. See the example below for basic operation.

Finally the widget() function contains the code that will be rendered to the sidebar when the widget is added. This is what your visitors will see when viewing your page.

Let's have a look at a very simple example "Hello World" widget.

WordPress Widget Example

This example shows how to create a widget which outputs "Hello World" to the sidebar. It also demonstrates adding a user configurable title setting to the widget in the administration panel, saving and retrieving user settings and displaying the widget.

It shares the same structure as the basic example above, but has been expanded to include the entire widget code. Simple copy and paste this into a text file called SampleWidget.php and upload it to your plugins folder. You can then activate and play around with it.

  1.  
  2. <?php
  3. /*
  4. Plugin Name: Sample WordPress Widget
  5. Plugin URI: http://timtrott.co.uk/
  6. Version: 1.0
  7. Description: How to create a WordPress Widget
  8. Author: Tim Trott
  9. Author URI: http://timtrott.co.uk/
  10. */
  11.  
  12. class Sample_Widget extends WP_Widget
  13. {
  14.   function Sample_Widget()
  15.   {
  16.     $widget_ops=array('classname'=>'Sample_Widget','description'=>'My Sample Widget Description');
  17.     $this->WP_Widget('Sample_Widget','My Sample Widget',$widget_ops);
  18.   }
  19.  
  20.   function form($instance)
  21.   {
  22.     $instance= wp_parse_args((array)$instance,array('title'=>''));
  23.     $title=$instance['title'];
  24. ?>
  25.   <p><label for="<?php echo $this->get_field_id('title'); ?>">Title:<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>"/></label></p>
  26. <?php
  27.   }
  28.  
  29.   function update($new_instance,$old_instance)
  30.   {
  31.     $instance=$old_instance;
  32.     $instance['title']=$new_instance['title'];
  33.     return$instance;
  34.   }
  35.  
  36.   function widget($args,$instance)
  37.   {
  38.     extract($args, EXTR_SKIP);
  39.  
  40.     echo$before_widget;
  41.     $title=empty($instance['title']) ? '': apply_filters('widget_title',$instance['title']);
  42.  
  43.     if(!empty($title))
  44.       echo$before_title.$title.$after_title;;
  45.  
  46.     // Do Your Widgety Stuff Here...
  47.     echo"<h1>Hello World</h1>";
  48.  
  49.     echo$after_widget;
  50.   }
  51. }
  52. add_action('widgets_init',create_function('','return register_widget("Sample_Widget");'));
  53.  
  54. ?>
  55.  

In the Sample_Widget function (technically called the constructor) I created some configuration options which will help WordPress (and the users of your widget) showing a friendly title and description.

The form method takes in the current settings as the $instance so you can use this to output the current settings to the user so they can update.

The update method does not do anything too complex, if you add another setting property add a line in here for it otherwise it won't get updated.

Finally the widget method will generate the output for the widget. Notice the $args parameter, this is exactly the same as the $args parameter on the old style widgets. $instance contains the settings for this particular widget. If you need help on the $before_widget etc... please see the previous tutorial for explanations.

Creating WordPress Widgets

Creating WordPress Widgets

I hope this quick guide helps you to migrate your old code or to create fantastic new WordPress widget!

More Tutorials in Creating Your First Website

  1. Types of websites available
  2. Introduction to Web Hosting
  3. Registering Domain Names and Configuration
  4. Installing WordPress
  5. Setting Up New WordPress Site
  6. Installing WordPress Themes and Plugins
  7. Using Custom Fields
  8. Creating WordPress Themes
  9. Creating WordPress Plugins ⇦ You Are here
  10. 10 Essential WordPress Plugins
  11. WordPress Security 101

16 Responses to “Creating Widgets for WordPress”

  1. I attempted to install this Sample Widget and it fails. I copied the code directly from your post into my file after I entered the info manually (practice). Still, did not work.

    I am using WordPress 3.0.1

    Thank you.

  2. Pavelsays:

    Thank you for this article. It helped me to feel some gaps in my starting knowledge of WP.

  3. Gerardsays:

    Tim - I'm not sure if you covered it above, but can this code exist within functions.php or does it need to be bundled somewhere else? I'd like to create a widget to display recent posts with thumbnails, and bundle it with the theme I've created. What's the best way to achieve that?

    • Hi Gerard,

      When I do this I create the widget as a plugin, then create a widgets folder within the theme folder and include the widget file within functions.php

      include_once("widgets/SampleWidget.php");

      Hope that helps

  4. Chrissays:

    In an ideal world, I'll have time to play with this more!

    Thanks for the help though...

  5. Doug Esays:

    This was great man, I finally found something simple enough to deconstruct to make my own widget  :D 
    On the chance anybody is having the same problem as I, I've been trying to add my own html code somewhere to the widget that is the design to appear on the sidebar of my blog. In this example replace Hello World between the 's with your html. In your html replace the "s with 's

    Mine for example was a div containing a table with some classes and I couldn't figure out where to put this for the final output onto the sidebar.

  6. Nice! I followed through this and the previous two tutorials. Very helpful!

  7. Sabinsays:

    Thanks so much for putting this together, this example was tremendously helpful and really allowed me to get a solid foundation to expand from. I will be sure to mention you and your site in every WP plugin I make! Thanks again!

  8. bitacresays:

    Thanks so much for your WP plugin tutorial it really helped me get started coding widgets quickly. Just wanted to let you know your site is fantastic and I've put your site in the acknowledgements section of every plugin I've made so far.

    Really great work, thanks again.

  9. [...] only took a few hours of GTE (Google, Trial, Error). Much thanks to Tim Trott at Azulia Designs for this wonderful tutorial on coding WP 2.8+ plugins, which was exactly what I needed to figure this out. BUT ANYWAY... since [...]

  10. Great info. Thanks for updating last post about widgets  :) 

  11. Nameless666says:

    Thank you for you tutorials I find this very useful. you simplicity create the power of your posts
    thank you again for this as work.

  12. Jacobsays:

    Great tutorial, easy to follow and use. Then you dont have to invent the deep plate again  :-) 
    Thank you

  13. Deansays:

    Excellent post. Thank You.

    I simply created a folder undre plugins folder and copied the php file into there and it worked straight away  :-) 

    Now hacking it around to build a schools newsboard widget

  14. PhilippISNsays:

    You may use the __construct keyword instead of the classname; and also, it is good practice to call the constructer of your super class. I also prefeer to use public/private etc. keywords for the members

    Example:

    public function __construct()
    {
    parent::__construct('Sample_Widget','Sample Widget',
    array('description' => __('This is the widget description',''),));
    }

    But good article  :-)  and thanks alot!

  15. mariasays:

    I copy your code and works but I change for my blog and I get message each time:

    Warning: Missing argument 2 for WP_Widget::__construct(), called in wp-includeswidgets.php on line 320 and defined inwp-includeswidgets.php on line 93

    What is not working? Thx

Leave a Reply