Website development and design blog, tutorials and inspiration

Creating Widgets for WordPress

Creating WordPress Widgets for your theme or plugin

By , Written on in PHP

Creating Widgets for WordPress

WordPress Widgets are a form of a plugin 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 clicks 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.

  2. <?php
  3. /*
  4. Plugin Name: Sample Wordpress Widget
  5. Plugin URI:
  6. Version: 1.0
  7. Description: How to create a Wordpress Widget
  8. Author: Tim Trott
  9. Author URI:
  10. */
  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. }
  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. }
  29. function update($new_instance, $old_instance)
  30. {
  31. $instance = $old_instance;
  32. $instance['title'] = $new_instance['title'];
  33. return $instance;
  34. }
  36. function widget($args, $instance)
  37. {
  38. extract($args, EXTR_SKIP);
  40. echo $before_widget;
  41. $title = empty($instance['title']) ? '' : apply_filters('widget_title', $instance['title']);
  43. if (!empty($title))
  44. echo $before_title . $title . $after_title;;
  46. // Do Your Widgety Stuff Here...
  47. echo "<h1>Hello World</h1>";
  49. echo $after_widget;
  50. }
  51. }
  52. add_action( 'widgets_init', create_function('', 'return register_widget("Sample_Widget");') );
  54. ?>

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!

Last updated on: Wednesday 21st June 2017

  1. maria

    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. PhilippISN

    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. Dean

    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. Jacob

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

    Thank you

  5. Nameless666

    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. Bruno Rico
    Bruno Rico

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

  7. bitacre

    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. Sabin

    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. Alan Trulock
    Alan Trulock

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

  10. Doug E
    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. Chris

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

    Thanks for the help though...

  12. Gerard

    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. Pavel

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

  14. randaweb

    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.