I have seen some good tutorials on creating widgets for WordPress 2.8 floating around the WordPress-o-Sphere. But, I didn’t feel any of them really covered practical usage. I want to show you how to create a widget for real-world development using WordPress 2.8’s new widget class.
In this tutorial, I’ll walk you through the steps of setting up a widget, its settings form, and displaying it on your site. At the end of the tutorial, you can download an example plugin to build from. Of course, you can apply this to your themes as well.
If you don’t feel like reading through the tutorial, skip to the end and download the example widget. It’s heavily commented and will give you a good base to build from.
What will the example widget do?
For the sake of the tutorial, we’ll be creating something extremely simple, yet you’ll see some advanced techniques on how to give users more control over the display of the widget through the widget controls.
Our widget will display a person’s name and sex. The controls will allow for the input of a widget title (text input), the input of the user’s name (text input), the selection of the person’s sex (select box), and whether the sex should be shown publicly (checkbox).
Here’s what the output of the widget will look like:

I know, it’s not much, but you’ll be able to take these tools and apply them to more complex widgets.
Loading the widget at the appropriate time
The first thing we have to do is load our widget when necessary. WordPress provides the widgets_init action hook that will allow us to do this. In WordPress 2.8, this action hook is fired right after the default WordPress widgets have been registered.
<?php
/* Add our function to the widgets_init hook. */
add_action( 'widgets_init', 'example_load_widgets' );
/* Function that registers our widget. */
function example_load_widgets() {
register_widget( 'Example_Widget' );
}
If you wanted to create more than one widget, you’d use the register_widget() function for each widget inside of the example_load_widgets() function.
Setting up our widget
In the past, creating widgets in WordPress was some ugly mish-mash of functions that was incomprehensible. In 2.8, we simply have to extend the preexisting WP_Widget class. So, the first step is creating a new class with a unique name.
class Example_Widget extends WP_Widget {
Then, we’ll want to add our first function. This function will be what makes our widget unique to WordPress, and it’ll allow us to set up the widget settings.
Note that the class name and first function name are the same. In this example this is Example_Widget.
function Example_Widget() {
/* Widget settings. */
$widget_ops = array( 'classname' => 'example', 'description' => 'An example widget that displays a person\'s name and sex.' );
/* Widget control settings. */
$control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'example-widget' );
/* Create the widget. */
$this->WP_Widget( 'example-widget', 'Example Widget', $widget_ops, $control_ops );
}
You’ll want to make some of this stuff unique to your widget.
Displaying the widget
The next function within our Example_Widget class will handle the display of the widget. This code might be a little confusing because we don’t know what it all means (we haven’t added the controls).
The goal here is to take the settings supplied by what the user selected for the widget and display the widget according to those values.
It’s also important to make sure you use the $before_widget, $after_widget, $before_title, and $after_title variables. These are provided by the theme and should not be hardcoded. How widgets are displayed should always be handled by the theme.
function widget( $args, $instance ) {
extract( $args );
/* User-selected settings. */
$title = apply_filters('widget_title', $instance['title'] );
$name = $instance['name'];
$sex = $instance['sex'];
$show_sex = isset( $instance['show_sex'] ) ? $instance['show_sex'] : false;
/* Before widget (defined by themes). */
echo $before_widget;
/* Title of widget (before and after defined by themes). */
if ( $title )
echo $before_title . $title . $after_title;
/* Display name from widget settings. */
if ( $name )
echo '<p>Hello. My name is' . $name . '.</p>';
/* Show sex. */
if ( $show_sex )
echo '<p>I am a ' . $sex . '.</p>';
/* After widget (defined by themes). */
echo $after_widget;
}
Making sure our widget is updated and saved
In this step, we’ll take each of our widget settings and save them. It’s a pretty simple procedure. We’re just updating the widget to use the new user-selected values.
If you’re using something like a text input in your form and users shouldn’t add XHTML to it, then you should add the value to the strip_tags() function as shown below.
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
/* Strip tags (if needed) and update the widget settings. */
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['name'] = strip_tags( $new_instance['name'] );
$instance['sex'] = $new_instance['sex'];
$instance['show_sex'] = $new_instance['show_sex'];
return $instance;
}
Creating widget controls or settings
The reason the new widget class in WordPress 2.8 is so cool is how easy it is to set up controls for your widgets. The get_field_id() and get_field_name() functions handle most of the dirty work, leaving us to concentrate on more important things like actually creating the widget. Take special notice of how these functions are used because it’ll make life much simpler for you.
First, we might want to set up some defaults. By setting up defaults, we can control what’s shown just in case the user doesn’t select anything.
function form( $instance ) {
/* Set up some default widget settings. */
$defaults = array( 'title' => 'Example', 'name' => 'John Doe', 'sex' => 'male', 'show_sex' => true );
$instance = wp_parse_args( (array) $instance, $defaults ); ?>
The first two parts of the form will be text inputs: the widget title and the person’s name.
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>">Title:</label>
<input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" style="width:100%;" />
</p>
<p>
<label for="<?php echo $this->get_field_id( 'name' ); ?>">Your Name:</label>
<input id="<?php echo $this->get_field_id( 'name' ); ?>" name="<?php echo $this->get_field_name( 'name' ); ?>" value="<?php echo $instance['name']; ?>" style="width:100%;" />
</p>
The second part of the form will be a select box, allowing the user to select their sex.
<p>
<label for="<?php echo $this->get_field_id( 'sex' ); ?>">Sex:</label>
<select id="<?php echo $this->get_field_id( 'sex' ); ?>" name="<?php echo $this->get_field_name( 'sex' ); ?>" class="widefat" style="width:100%;">
<option <?php if ( 'male' == $instance['format'] ) echo 'selected="selected"'; ?>>male</option>
<option <?php if ( 'female' == $instance['format'] ) echo 'selected="selected"'; ?>>female</option>
</select>
</p>
The last part of the form will show a checkbox that allows the user to select whether they want to display their sex publicly.
<p>
<input class="checkbox" type="checkbox" <?php checked( $instance['show_sex'], true ); ?> id="<?php echo $this->get_field_id( 'show_sex' ); ?>" name="<?php echo $this->get_field_name( 'show_sex' ); ?>" />
<label for="<?php echo $this->get_field_id( 'show_sex' ); ?>">Display sex publicly?</label>
</p>
The only step left is closing off the form function and the rest of the widget code.
<?php
}
}
?>
Time to create your own widgets
If you’ve ever created or attempted to create a widget in WordPress prior to 2.8, then you can probably see how much easier this is. To help people learn the new system, I’ve put together an example widget. I’ve left loads of comments about what code does what in the file, so it should be pretty easy to follow:
I’m enjoying working with the new widget class. I almost feel motivated to release a few new widgets in the near future. But, I’d love to see what all you come up with.



I’m going to have to read that again when I am not so tired..
Good write up.
[...] Justin Tadlock has a nice tutorial on the new way to create WordPress Widgets in WP 2.8. You might remember that in the upcoming version of WordPress the admin interface for Widgets has been revamped, but the method of developing Widgets has been updated as well. [...]
As usual, Justin: great great article!
Stefano
[...] Completeguide to creating widgets in WordPress [...]
[...] Guia para Criar Widgets – tutorial detalhado sobre a criação de widgets para o WordPress 2.8 (em inglês). [...]
Enjoy exploring new things and the reason I do love WordPress is that every major release is making even better application.
Back to the topic, I agree that writing a widget in the WP releases prior 2.8 was really very nasty and unorganized job full of messy functions and dozens of variables.
I understand things by getting them in my hands first, I have downloaded your code, and it seems as its the sole teacher to understand the tip.
Thanks for all the good stuff, bro.
[...] original here: The complete guide to creating widgets in WordPress 2.8 You May Like Linking To UsHello and welcome to our blog, you may consider linking to us, because [...]
[...] by WP Greet BoxJustin Tadlock wrote a good tutuorial on how to write widgets in Wordpress 2.8. Go here now to check it [...]
As always Justin, you rock. I’m mildly techie, but I think with your excellent instructions I could do this!
The Frosty — It’s definitely a lot to take in at once. I had considered not writing it because of all the code.
Stefano — Thanks. I’m glad you like it.
J Mehmett — I much more enjoy getting my hands dirty with the code too. I hope it’s documented well enough to help you build your own widgets in WordPress 2.8+.
Randa Clay — It shouldn’t be too tough once you understand how each function works within the individual widget class. Mostly, I like how everything is separated and a lot cleaner than it used to be.
Thanks for the wonderful break down, this helped me recreate two of my widgets so far (twitter and feedburner). It’s so much easier than WordPress 2.7.
One problem I encountered is adding onfocus, and onblur to an input field, what would be the properly formatted code? Any help would be appreciated.
[...] Tadlock has three posts on WordPress 2.8 already – The Complete Guide to Creating Widgets in 2.8, Custom Taxonomies in WordPress 2.8, and Tag Descriptions in WordPress [...]
Matt — I would guess you’d add the code the same way you normally would. I can’t think of any reasons how being a part of a widget would make any difference.
@Justin: I thought so too, but when I added this
value="Enter your e-mail address" onfocus="if (this.value == 'Enter your e-mail address') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Enter your e-mail address';}". When using the code as is, it gives the following error: syntax error, unexpected T_STRINGMatt — That has nothing to do with the widget system. You need to learn how to handle strings in PHP or switch between PHP and XHTML if that’s the error you’re getting.
Thanks for the link Justin, I got it to work.
[...] The complete guide to creating widgets in WordPress 2.8 (tags: wordpress) [...]
WoW this is great. I will have to read it again and try along with it ,but I always wanted to make a widget. Something new to learn about Wordpress. Thanks Mr Tadlock!
[...] to create fake registered sidebars anymore. Just use the_widget template tag. This means you can create a custom widget and insert it anywhere you want. The new widget treatment makes an old dream of some WordPress [...]
Hi
Thanks for your guide. I have followed your guide and managed to create multiple instances of the plug-in and had then displayed them on different sidebars.
But when I try to change the options on one widget on a sidebar … the changes will automatically apply to all the instances of widgets on all other sidebars!?
Do you have an idea on how to allow the plug-in handle multiple instances of widgets? Or …
Anyway, I have learnt a lot for the first time about Widget once read this guide. Thanks again
Leon
chantelle tamaris — Good luck with making your widget. It shouldn’t be too tough with this code.
leon — You don’t have to do anything for multiple-instance widgets. This is automatically done in 2.8 using the new widget class.
[...] That’s why Justin Tadlock has written “The complete guide to creating widgets in WordPress 2.8″. [...]
[...] The complete guide to creating widgets in WordPress 2.8 [...]
[...] Guide to create Widgets in Wordpress 2.8 [...]
This post was really helpful. Thank you! I do have a question though
How do you add wysiwyg controls to a widget? I’ve tried taking apart a few old plugins – but they don’t use the new 2.8 widget class, so things get kind of messed up. They also seem to link to their own version of tinymce which doesn’t make sense to me, since there is already tinymce bundled with wordpress… why not make use of that? Hoping you can help…
[...] 2. The Complete Guide To Creating Widgets in WordPress2.8 – Justin Tadlock [...]
Jennifer — I absolutely hate the WYSIWYG editor, so I’ve never done any work with it.
I don’t imagine it’d be too tough to load on the admin side of things; I’m just not sure how to do it.
I have been able to get tinymce to show up in a textarea of a widget – but when I go to save the widget – it doesn’t seem to save the changes – and then reverts the box back to the non-tinymce view. I’m beginning to think now that this may be some kind of issue with the widget class/feature itself – because that just sounds REALLY odd… I’m not a fan of the wysiwyg editor myself – but my clients can’t do HTML – so I need to have it there for them.
Excellent and easy tutorial. Thanks a lot!
Ok, despite the excellent tutorial, I don’t get it. I’ve created a widget, but when I try to save it, it doesn’t. It looks like it works, but it doesn’t appear on the page and if I reload the widget page, it has disappeared from the sidebar.
The widget is exactly like your example widget, which of course works perfectly. Any ideas what could cause behaviour like this?
I also love the new widgets API and the new features on WP 2.8.
I have bookmarked this post as I will have to read this a couple of times and try and test to see if it works. I would like to create my own widgets as some plugin developers don’t have widgets for the work.
Thanks for sharing this
[...] 2. the complete guide to creating widgets in wordpress2.8 – justin tadlock [...]
Justin, thanks for the explanation “for dummies” – I really needed it. It seems that WP lacks of better function description and documentation overall… I deal a lot with Drupal, have to say that their API documentation service seems much superior to me than WP.
Anyway, I’m kinda stuck with updating my own plugin to be compatible with the 2.8 – new widget instances showing up in widgetized areas just fine, but the existing widgets (created in previous WP version) don’t show up and I have no clue why. I output the var_dump for the get_option(”my_widget”) and can see all the existing and the new widgest arrays, but only the new ones show up in the widgets section and the front end. Seems like I can’t even grab their $instance(s). Any thoughts on this?
Thanks again for the post!
Hello ,
its a very good stuff for widgets but how to add this widget or how to install this kind of widget in wordpress 2.8
Thanks
Great Stuff !!!!!!!!!!!!
There is nothing getting stuck at any point……….
I have created lot of widgets using this one structure…….
Thanks for a great guide! I started my first wordpress widget this week with another template that unfortunately wasn’t ready for the 2.8 widget api changes. But in about an hour I transferred over the work I had done earlier and I now have a multi-instance widget saving and retrieving all the settings I need for the widget I’m creating.
Thank you!
[...] Widgets work – including a easier to use API. In light of this, I made use of the new API (armed with this great tutorial and sample file) and created some custom widgets for my [...]
Thanks Justin. This was a nice little tute to get me fast-tracked onto making some custom WP 2.8 widgets.
Cheers!
I want to create a widget to send sms, for blog. but I want to give this feature only to registered user, how to get user registration data? how I check user is loged in or not?
[...] I wanted to have for the BookMooch widget. But after searching around a little bit I found another widget template over at Justin Tadlock’s site. By taking the plugin control structure I’d already [...]
[...] 2.8 Resources For Developers | W3Avenue The complete guide to creating widgets in WordPress 2.8 Wordpress 2.8 And 10 Things That You Should Know Before/After You Upgrade 10 WordPress 2.8 Features [...]
Can widget be used as part of the loop?
I’m new to wordpress, so here’s what i want to do.
Let’s say I have two loops on my page.
one for displaying important post (6 post)
another for just daily news (12 post)
If i’m in the important part and I want to see 6 more post, I click on the page 2 navigation from that section. But I only want that section to reload.
Are widgets capable of this?
[...] 2. the complete guide to creating widgets in wordpress2.8 – justin tadlock [...]
[...] Tadlock wrote a very comprehensive article about making widget in 2.8 and I will use this to make a widget that displays only posts from a [...]
Hi
Please tell me how to create a drop-down author list widget, similar to categories widget.
Thank you.
[...] The complete guide to creating widgets in WordPress 2.8 (tags: wordpress widgets howto widget development reference tutorial) [...]
[...] still work, but you no longer have to specify them for multiple use. They all are now. Check out the complete guide to creating a widget from Justin [...]
Mikko — You just have to take it one step at a time. I personally test widgets with just about every change I make because it’s so easy to make a mistake.
George Serradinho — Let me know what you come up with. I really wish more plugin authors would add widgets to their plugins. So many of them could use widgets.
Max — I’m not sure about older widgets. I would suggest just converting everything to the new Widget API rather than worrying over it.
Vasudevbbhat — WordPress 2.8 brought back the drag-and-drop interface, so you only have to drag widgets over now.
Nimesh Kumar — I’m glad you’ve put the tutorial to good use.
Jon Pruett — Cool. This would’ve been much harder on WordPress 2.7, so I’m happy you’ve been able to convert everything.
Mark — I’m glad you’ve found it useful and were able to create some custom widgets.
smsfame.com — Check out the WordPress support forums.
Edgar Doiron — You’ll have to work on your explanation. I have no idea what you’re asking.
P.Raman — Yeah, I’ll get right on that.
It looks like a neat tutorial, but I’m missing something I haven’t been able to find in any tutorial, namely where do you save your widget code?
I’ve created my first widget after reading this post,a widget which shows if the owner of the blog it’s able for freelancer . It’s a very good tutorial ,you are great .
@Justin -
http://coffeeman.name/wp_test/
let’s say i want two navigation, one for the top part and one for the bottom part. And having them work independantly?
[...] 11.The complete guide to creating widgets in WordPress 2.8 [...]
Thanks for your tutor mate
i’ll make it
[...] The complete guide to creating widgets in WordPress 2.8 [...]
[...] 11.The complete guide to creating widgets in WordPress 2.8 [...]
Good post for blogger beginners and particularly i like your template which seems to be very elegant for me…
Thanks for sharing and many more years to come/ your friend krishna das
Sorry, one more time- why you’ve not added any ads?
As a blogger who spends hours playing with WP I found this intriquing.
I am not a comuter prog techie sort but i could follow these instructions and make a good attempt. Maybe i should do that.
Thanks for the share.
Kevin
I knew there was a good reason why this article/post was in the Top 10 on Stuff-to-Tweet. Nice job Justin. Since my cracker skills are meager at best, I figure I’ll have to send my Rent a Coder buddy here so he can brush up on your How To Make a Widget Work in WP
How many of your reader’s have asked you what your hourly rate is? BTW, what is it?
[...] The complete guide to creating widgets in WordPress 2.8 (tags: wordpress tutorial webdevelopment widgets wordpress_widgets) [...]
Excellent guide to start with wordpress . At firt i feel so tired . Nowwith this tutorial everything is clear .
[...] http://justintadlock.com/archives/2009/05/26/the-complete-guide-to-creating-widgets-in-wordpress-28... [...]
This is fabulous! Thank you so much!
One point of confusion though – there is a discrepancy between the code you show in the post, and the code inside the downloadable example –
What is the difference between using echo and printf (besides printf using more code)?
Justin, many thanks for the tutorial – I looked a lot to find how to do this.
Great and complete tutorial Justin,like always thank you!
Stéphane Gallay — The reason you won’t find this in tutorials is because people that code widgets generally know this. Where to put your widget code depends on what you’re doing. Are you adding it to a theme? Are you adding it to a plugin?
Ditutu — Thanks. I’m glad you found it useful.
Edgar Doiron — I still don’t know what you’re asking and what it has to do with coding a widget.
Johnny Goodperson — Good luck with creating your widget.
Joe Random — I don’t want ads.
Kevin Baker — Hope it works out for you. Good luck with creating a custom widget.
JNFerree — Make sure to have him download the example widget. Most coders will probably like to dive right into the code.
I don’t have an hourly rate though. I do pricing based on the project.
Joe Somebody — I hope this tutorial at least took a little weight off your shoulders then.
cas — The widget download is localized (
__()), so that developers will remember to localize their themes/plugins when creating widgets. The tutorial was written a bit more for the average user.Laura — I’m glad you managed to find the tutorial.
Jane Doe — You’re welcome. I’m glad you liked it.
Do you know any special plugins to create these widget .That might save a few minutes since i am not much familiar with php and other code?
Ah ha! Well, now that makes sense. I see that I have a lot to learn yet about plugins and widgets and Wordpress in general – Thanks so much for taking the time to explain that!
Thanks that was just what I needed
You created a nice and clean example that was very easy to follow.
I did have one issue but it wasn’t with your code it was with the text editor(visual studio) I was using, switched to phpDesigner and now everything works fine.
Very good tutorial for me as a newbee.
I wonder is there any program or plugin to make widget in wordpress?.
Hey
I just want to say thank you! Once I followed it through bit by bit, I began understanding it a lot better, and I’ve nearly completed my first widget.
Oh, and a little tip for anyone else trying to learn this stuff – don’t just copy paste it. Type it all out bit by bit – it’s invaluable to understand what’s actually going on. That’s applicable to anything really, not just WordPress.
-Adz
Hello Justin,
I go through your most of the articles and frankly speaking, those are really nice..
I hope you can solve my one problem.
I have a plug-in named MM Snippet.
In Appearance section on widget link, we have list of available widget to be displayed in side bars. In the bottom of the page, the plug-in provides no of Snippets.
see this link :
http://www.drivehq.com/file/DF.aspx/376855287.gif?isGallery=&share=&shareID=0&fileID=376855287
Now the problem is that in available widget page only one snippet is shown. Rest of the snippets are ignored by a condition in function wp_list_widgets()
This function resides in wp-admin\includes\widgets.php file.
If I comment the below lines, it works great but I am limited to plug-in only.
if ( in_array( $widget['callback'], $done, true ) ) // We already showed this multi-widget
continue;
I can’t touch the wordpress core code.
Kindly help..
Thanks,
Gaurav
Deleted by the administrator. Please don’t post the same comment twice. This is not much different than having to deal with spam comments on a daily basis.
Gr8 stuff….will surly try it out…..sweet and simple
Hello Justin, first let me say how usefull I have found this tutorial.
Now I managed to follow it and create my own widget succesfully but one little thing. I have a select drop down with options and when I select an option other than the default and hit save although it does save and displays my selection correctly the option in the select drop down (in the widget box-admin) reverts to the default. I think that is confusing for users.
Then I though let me try your example and see if that happens with your example widget and how strange. It does! I choose female from the drop down and it does save and display correctly however the option in the drop down still shows male.
Is there a way to fix this little detail? I appreciate any responce to this.
[...] The complete guide to creating widgets in WordPress 2.8 – An excellent article from Justin Tadlock, a WP Demi-God. Related Posts:Links for December 15thLinks for July 17thLinks for June 16thLinks for August 4thLinks for February 9th Share This: [...]
[...] reading Justin Tadlock’s tutorial: The complete guide to creating widgets for WordPress, I have created eleven custom WordPress 2.8 widgets. It’s actually quite simple, much easier [...]
Very good tutorial for me, I wonder is there any program or plugin to make widgets for wordpress blogging platform.
Wow, thanx for this tutorial! I can’t wait to get my hands on this at evening!
Very nice tutorial. I am trying to extend this and provide file upload by adding a new form item with type=”file”. My form displays and I can choose a file to upload, however I don’t know how to pull out the file information in the update() method. I also cannot find a single example of a 2.8 widget with file upload capability. Any pointers please ?
Here is one for you. Used this code to develop a plugin for use with my Wordpress MU install. The problem is though that when I change the values of parameters on one blog it changes it on all of them.
Just wanted to say “Thanks” for this post, I found it very helpful with adding / creating widget functionality in the plugins I recently wrote.
Since reading this post a week and a half ago, I have been able to put three plugins into the WordPress repository.
Kudos to you!
[...] The complete guide to creating widgets in 2.8, Justin Tadlock [...]
[...] The complete guide to creating widgets in WordPress 2.8 [...]
Hi,
I could not find any information on how to install new widget (not present in WP 2.8.4)
I downloaded a new widget, but don’t now where to put it. Does it go to a theme directory?
Thanks
@ Len,
You add the file to your plugins directory or add the coding to the bottom of your functions.php file in your theme’s folder (This would make it only available on that theme).
Thanks for the writeup. It helped me out a lot.
This is great. Specially very good tutorial for me.
Thanks….
[...] For more information on how you can write your own WordPress widget, Justin Tadlock wrote up an awesome article on the subject. [...]
[...] Widget selbst erstellen (Wordpress 2.8) http://justintadlock.com/archives/2009/05/26/the-complete-guide-to-creating-widgets-in-WordPress-28 Tweet This!Share this on TechnoratiSubmit this to NetvibesAdd this to Mister WongMark this on [...]
[...] The complete guide to creating widgets in WordPress 2.8 have seen some good tutorials on creating widgets for WordPress 2.8 floating around the WordPress-o-Sphere. But, I didn’t feel any of them really covered practical usage. I want to show you how to create a widget for real-world development using WordPress 2.8’s new widget class. [...]