Creating WordPress Widgets

Last Updated January 17, 2019 by . First Published in 2010.

Creating Your First Website Series
  1. What are the types of website available
  2. Introduction to Web Hosting
  3. Registering Domain Names and Configuration
  4. Installing WordPress Self Hosted Tutorial
  5. Setting Up New WordPress Site
  6. How To Install WordPress Themes and Plugins
  7. Using WordPress Custom Fields
  8. Creating WordPress Themes
  9. Create Custom WordPress Shortcodes
  10. Creating WordPress Widgets
  11. WordPress Security 101
  12. 10 Essential WordPress Plugins for 2018
  13. 12 Best Free WordPress SEO Plugins and Tools

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.

Creating WordPress Widgets

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.

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

php
<?php
/*
Plugin Name: Sample Wordpress Widget
Plugin URI: https://timtrott.co.uk/
Version: 1.0
Description: How to create a Wordpress Widget
Author: Tim Trott
Author URI: https://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'];
?>
  <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>


<?php
  }
 
  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.

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

Comments

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.

This post has 15 comment(s). Why not join the discussion!

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.

  1. MA

    On Saturday 22nd of December 2012, maria said

    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 93What is not working? Thx
  2. PI

    On Thursday 24th of May 2012, PhilippISN said

    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 membersExample:public function __construct() { parent::__construct('Sample_Widget','Sample Widget', array('description' => __('This is the widget description',''),)); }But good article :-) and thanks alot!
  3. DE

    On Monday 16th of April 2012, Dean said

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

    On Monday 2nd of April 2012, Jacob said

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

    On Friday 24th of February 2012, Nameless666 said

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

    On Tuesday 14th of February 2012, Bruno Rico said

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

    On Tuesday 6th of December 2011, bitacre said

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

    On Sunday 27th of November 2011, Sabin said

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

    On Sunday 7th of August 2011, Alan Trulock said

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

    On Sunday 20th of March 2011, Doug E said

    This was great man, I finally found something simple enough to deconstruct to make my own widget :DOn 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 'sMine 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. CH

    On Wednesday 16th of March 2011, Chris said

    In an ideal world, I'll have time to play with this more!Thanks for the help though...
  12. GE

    On Thursday 10th of March 2011, Gerard said

    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. Lonewolf Online

      On Thursday 26th of May 2011, Lonewolf Online  Post Author replied

      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.phpinclude_once("widgets/SampleWidget.php");Hope that helps
  13. PA

    On Sunday 28th of November 2010, Pavel said

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

    On Sunday 7th of November 2010, randaweb said

    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.1Thank you.