Tim TrottTim TrottFree your mind

Creating Widgets for WordPress

By , Wednesday 28th April 2010 in 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.

class Sample_Widget extends WP_Widget 
  function Sample_Widget() { }
  function form($instance) { }
  function update($new_instance, $old_instance) { }
  function widget($args, $instance) { }
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.

Plugin Name: Sample WordPress Widget
Plugin URI: http://timtrott.co.uk/
Version: 1.0
Description: How to create a WordPress Widget
Author: Tim Trott
Author URI: http://timtrott.co.uk/
class Sample_Widget extends WP_Widget
  function Sample_Widget()
    $widget_ops = array('classname' => 'Sample_Widget', 'description' => 'My Sample Widget Description');
    $this->WP_Widget('Sample_Widget', 'My Sample Widget', $widget_ops);
  function form($instance)
    $instance = wp_parse_args((array) $instance, array( 'title' => '' ));
    $title = $instance['title'];
  <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>
  function update($new_instance, $old_instance)
    $instance = $old_instance;
    $instance['title'] = $new_instance['title'];
    return $instance;
  function widget($args, $instance)
    extract($args, EXTR_SKIP);
    echo $before_widget;
    $title = empty($instance['title']) ? '' : apply_filters('widget_title', $instance['title']);
    if (!empty($title))
      echo $before_title . $title . $after_title;;
    // Do Your Widgety Stuff Here...
    echo "<h1>Hello World</h1>";
    echo $after_widget;
add_action( 'widgets_init', create_function('', 'return register_widget("Sample_Widget");') );

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 Widgets for WordPress
Creating Widgets for WordPress

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

My website and its content are free to use without the clutter of adverts, tracking cookies, marketing messages or anything else like that. If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

About the Author

Tim Trott

Tim is a professional software engineer, designer, photographer and astronomer from the United Kingdom. You can follow him on Twitter to get the latest updates.

Further Reading
16 thoughts on “Creating Widgets for WordPress”
  1. Tim Trott

    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

  2. Gravatar

    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


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

    But good article  :-)  and thanks alot!

  3. Gravatar

    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

  4. Gravatar

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

  5. Gravatar

    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.

  6. Gravatar
    Bruno Rico

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

  7. Gravatar

    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.

  8. Gravatar

    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!

  9. Gravatar
    Alan Trulock

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

  10. Gravatar
    Doug E

    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.

  11. Gravatar

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

    Thanks for the help though...

  12. Gravatar

    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?

    1. Tim Trott
      Tim Trott

      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


      Hope that helps

  13. Gravatar

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

  14. Gravatar

    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.

Leave a Reply

Your email address will not be published.