How To Create A Widget Plugin For WordPress

How To Create A Widget Plugin For WordPress

  • Published on: 5th November 2012
  • Author:
  • Under: Other
Post Series: How To Create A Widget Plugin For WordPress
  1. 1.How To Create A Widget Plugin For WordPress
  2. 2.How to Create a Widget Plugin for WordPress – Part 2

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:

  1. The constructor, to initiate the widget
  2. The form() function to create the widget form in the administration
  3. The update() function, to save widget data during edition
  4. 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 →

Remi
Remi is an expert WordPress developer that coded many great free and premium themes and plugins. His experience on WordPress allows him to produce great stuff and to propose advanced tutorials. (remicorson.com)
Remi
This article has 35 comments
  1. Gregg says:

    Great tutorial AJ. – Thanks!

    1. AJ Clarke | WPExplorer says:

      You’ll have to thank our awesome new Contributor “Rémi Corson” ;)

      Admin
  2. Dawson says:

    Very time article and I’m scratching my head how this plugin thing works. Thanks for writing a detailed article. Kudos.

    1. Remi says:

      Hi, if you need some help let us know!

      Author
  3. behzad says:

    Hi Aj, Thanks for share this post

  4. Bucur says:

    very nice tutorial AJ congratulations

  5. Mike Keating says:

    Thanks so much AJ and Remi. This is awesome. Keep up the great work. Love what you are doing :)

    1. Remi says:

      Thanks Mike!

      Author
  6. Tino says:

    very useful. tahnks…

  7. David – Closemarketing says:

    Nice Tutorial… I’m going to use it Soon!
    Regards.
    David

  8. stacey says:

    You just simplified something that had my brain in knots. Thank you thank you thank you!

  9. Clarke Design says:

    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 ?

    1. Remi says:

      can you share a bit your code pastebin or github gist?

      Author
  10. romey says:

    Awesome….. tanx

  11. Joe says:

    Really good tutorial, very clear and easy to modify. Cheers

  12. Gaetano says:

    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!

    1. Remi says:

      Many thanks!

      Author
  13. DrV says:

    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!

    1. Remi says:

      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.

      Author
  14. tommytx says:

    and in my next post I’ll show you how to add more complex field types
    Hi,
    Thanks for the great detailed post. did you ever get around to doing more as you promised… URL please. love your work.

  15. chris says:

    Anyway to use the $title variable as the widget name in the constructor? I plan on having many instances of the same widget in my sidebars. This would add a unique title to each.

    1. AJ Clarke | WPExplorer says:

      If you need for this is for styling/javascript, then I would recommend just adding an ID to whatever wrapper you are using for the widget (div id=”social-widget-$title). I don’t see any point in using it in the “constructor”.

      Admin
  16. Yanis Christodoulou says:

    Perfect tutorial, thank you very much Remi :)

  17. Cary Kelly says:

    Thanks Remi for the great tutorial. I’m having some problem with my widget though; after activating the plugin, none of my widgets (including the custom one) will stay open on the WordPress widget page. I can view the title box for each widget, but upon clicking the dropdown by each name, no information will display–for any widget! The problem disappears after I deactivate the custom plugin. I have my code up here: https://gist.github.com/nightwalker5/0a8f90e9fa2e7da3bf13
    Maybe I’ve just made a small mistake? I am just a beginner in the world of PHP and WordPress.

  18. akexis says:

    *Claps*

    Finally a tutorial that doesn’t assume you know to place your code in the plugins folder. It doesn’t assume you know what the functions are for. A great tut for getting off the ground and running. You kept it simple, gave great example code and explained what the different sections are doing.

    Awesome. Thanks.

  19. Remi says:

    Many thanks! ;-)

    Author
  20. Kumaresh Cool says:

    Thanks for the tutorial ….

  21. Agent Bey says:

    Great tutorial! One simple question. I am unable to see the widget name and description under the Available Widgets. The widget name is blank. All else is working properly.

    How do I correct that?

  22. Agent Bey says:

    Disregard my last message. It was answered in part two. Very clear and concise. And I have already have my widgets running.

    1. AJ Clarke | WPExplorer says:

      Great! I am glad to hear that ;)

      Admin
  23. Ross Dallaire says:

    Nice tutorial! It worked on my first try.

  24. GratuiTous says:

    Great. Thank-you Remi :) — Awesome start to someone learning PHP + developing simple plugins!

Sorry, comments are now closed.