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.
As usual, Justin: great great article!
Stefano
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.
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.
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.
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!
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.
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…
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
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!
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?
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?
Hi
Please tell me how to create a drop-down author list widget, similar to categories widget.
Thank you.
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?
Thanks for your tutor mate
i’ll make it
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?
Excellent guide to start with wordpress . At firt i feel so tired . Nowwith this tutorial everything is clear .
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.
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!
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….
great tutorial. The new way of making widgets makes a lot of sense coming from a programming background
your download link appears to be broken.
hello,
Your download file contains only one file(example-widget.php). Is that sufficient to run this widget? I am getting the following error
“Call to undefined function add_action()”
could you please give me latst download version?
Thanks!
WOW Thank you sooo much I finally was able to get this working with my plugin!!!! You ROCK!!!
My plugin:
mp3 player plugin for wordpress
next version with these updates is 1.2.5 be on the lookout!
once again thank you so much!
Tom
clear explanation…Had some issues but all ok now
regards
Really nice tut! Been fighting with finding widgets I could use for custom needs.
I was able to use your widget and by replacing all “example” with a name of my own it’s working. It’s showing on the sidebar and doing exactly what it should. Thanks!
http://www.soakingplanet.com
Now for the fun part:
I’d like to have the widget be activated per user’s page. Is there a way it could be draw the info automatically from their registration?
Not sure if I say it right.
What I’m trying to create is a profile-maker for artists that would then show up on a single page using the format http://www.mydomain.com/artistname.
Any ideas?
thanks again!
Andre
Hi,
It seems that there was a modification of the
__checked_selected_helperfunction (wp-admin/includes/template.php) in wp 2.9. Theif ( $helper == $current)test as been replaced withif ( (string) $helper === (string) $current)test so thechecked( $instance['show_sex'], true )doesn’t work anymore ! I think that you will have to replace it withchecked( $instance['show_sex'], 'on' )for checkboxes to be checked again…Damn it ! If I’m right, we will have to rewrite many widgets code….
Thank you for all you do to teach wp to the community.
Seb.
yes. i believe that is true. urgh
yup. be careful of true vs ‘on’
in fact, it seems that on (without quotes) is also adequate.
seems like a simple #def true on
Bro you saved my life man.. yes this is true…
Thanks a million, man! This saved my day and I was able to widgetize and parameterize a hardcoded hack from a previous blog in under an hour, despite having no PHP experience.
Great guide Justin ! Thanks !
The widget works great, but I’m having a minor display issue in the WP 2.9 widgets panel.
See screenshot here: http://twitpic.com/yw8g9/full
Notice firebug displays inline styles: width: 330px; margin-left: -65px;
These inline styles are only being added to the example widget downloaded here, and not the other wordpress default widgets.
What could be causing this? How can I remove this inline code?
Thank you so much for this wonder full article. It really helped me a lot and made it so easy to create a re-usable widget in WordPress. Keep up the good work and you rock!!
Thanks for the tutorial, but I’d hardly call it the complete guide as you do not mention how to make it visible in the add widget screen.
There’s always someone that doesn’t read all of the post title: The complete guide to creating widgets in WordPress 2.8. I said nothing about it being a guide to registering widgets.
Nevertheless, how to get your widget to show in the widgets admin is clearly described in the tutorial above. Actually, it’s the first step.
It works! Thanks.
Is there a way to just add some default php code in the widget? I’m trying to create widget that will show subpages.
I’m putting this to good use for my theme site. Thanks for posting this up. I’ve customized it a bit. Once it’s released, I’ll shoot you a link. I appreciate you putting this article up, without it I would have been lost
Shit, sorry about commenting again so soon Justin.
I’ve got the widget working, but had a question. For those who want to write php codes directly into their theme without using a widget, how would I go about this? I know the code should be like this normally:
if(function_exists(‘function-name’)) { function-name(); }
But I can’t seem to figure out which function name I’m suppose to use and also, inside the function-name() I’d love to be able to allow the users to add their own name/sex right inside (ie: function-name(‘mike’,'male’);
Is this a simple fix, or something that takes a fair bit of editing?
Thanks for any help you can give Justin.
Mike, I don’t know exactly what you want to do, but you might want to take a look at this plugin: http://wordpress.org/extend/plugins/exec-php/
Cheers,
frq.
Hello, Justin, I know this article has been out for a while, but it really helped me. Thanks very much.
I noticed something though. My checkbox was not updating and was off all the time. I changed a little the code (copied from the default Text Widget) to something like this:
line 97, from:
to:
line 136, just the checked part of it, from:
to:
Then it started working. I don’t know if it has something to do with 2.9, but it worked for me that way.
Thanks again,
frq.
PS: Checking my writing for the last time before hitting the submit button got me wondering what one might think seeing just these lines of code with a variable called $show_sex
Well, i’ve put some ?php tags that got stripped out my comment. My bad. Here is the change in the code on line 136, inside the php tags of the checked part:
from:
to:
frq.
My Sex selectbox (male, female) isnt updating. I am using WP 2.9.2.
The checkbox “Show Sex” was also not updating until i read the comment of @frq.
What can be the reasons ?
Thanks.
i fixed it by replacing
$instance['format']
with
$instance['sex'] in selectbox drop down.
Thanks.
Also how can i make this widget singleton?. Like i want only once instance of this widget to be availabe in widget section.
I’ll be really grateful if somebody can help.
Thanks.
Hey thanks for the post. I had no problem setting up a new widget with this method.
However, what I am ultimately trying to do is create the equivalent of the text_widget for the dashboard… like the Quick Press but for the sidebar.
I’ve read up on creating dashboard widgets (http://rick.jinlabs.com/2009/02/01/how-add-options-to-your-wordpress-27-dashboard-widgets/) and in the wp API but what I fail to catch is how and if dashboard widgets can stand in for the text widgets you find in the widgets panel.
This should be possible yes? Any ideas?
I think this could be very interesting for providing easier-to-use widgets for the user client.
Best,
Owen
Hi Justin
I’ve been playing around with the example widget code and trying to make a recent posts widget which uses data from custom fields. How do you get custom field data into a widget?
Awesome Post! Just what I needed. Extremely Clear and concise.
Thanks!
Important note about WordPress widget id_base names. DO NOT include capital letters in the id_base name. When the widget is registered, the id_base name appears to be stored in lower case letters as the wp-options key.
So the next time you refresh the widgets page or your website, you will not see your widget because WordPress is not looking for your id_base with the capital letter in it.
Just a helpful tip for anyone else who spent 2 hours trying to figure it out.
Hi,
I try to create my first widget with the help of your good tutorial.
With my widget I have an issue, it’s impossible to save widget options with IE8 !
When I test “Example Widget” I get the same issue, impossible to save the options.
Can you help me ?
Best regards
Hello,
Being very new to WordPress I have a obvious question.
Yes I downloaded your code, Yes I activated the widget in the admin panel but HOW exactly do I use it? Where do I see the form that allows to enter a name …. and will display name, sex etc. etc. A more detailed description of HOW to use widgets would be appreciated since this is an introductory tutorial.
Thanks,
Carly
I have to be honest that I am literally a beginner of PHP and I was able to use this tutorial to pull off a customizable widget for my wordpress blog.
Thank you for posting this, this is a great tutorial.
I am unable to get a widget I created to work properly. I followed the example in this article. The widget shows up just fine in the backend’s Appearence=>Widgets screen and I am able to drag it to one of my sidebars. What happens is that the widget’s output is not showing up on the front end (and I checked the HTML source and there is no sign of if it at all, not even the tags generated from the $before_widget and $after_widget variables). I checked apache’s error_log for possible PHP error messages. Nada. What also happens is if I navigate someplace else on the back end and then navigate back to the widget screen, the widget has vanished from the sidebar. I have been staring at this code for hours and hours and cannot see what is wrong.
Damn. The code seems to have been mangled. The code is available in this ZIP file: ftp://ftp.deepsoft.com/pub/deepwoods/Other/GAN_Widget.zip.
I’ve made some (minor mostly) changes to the GAN code. It still does not work. I made it into a plugin and it is available at ftp://ftp.deepsoft.com/pub/deepwoods/Other/GAN_Plugin-0.0.zip.
Thank God for this post, I needed a good framework to start with. Lots of stuff out there for earlier versions of WP, moving on to 3.0 I hope this all still holds true, thanks man.
OK, I must be a complete idiot. Where do you save the example widget file, or how do you get it to display in the admin widget area?
Well, to answer my own question, since I’m using WordPress MU, it apparently has to go under the mu-plugins directory.
I am using select box to list the category names in my widget.For instance ,select box list 3 categories.I have added 2 widget in my sidebar.When i click widget edit in admin page it displays the categories as in order.I want select box to display what i chosen for that widget . Please help me to fix this….
Can one tell “where the widget data is stored in Database”?
It is located in the wp_options table, the ‘option_name’ is widget_example-widget.
I have a second question, is it possible to change the ‘widget_’ prefix? Where is it in the code?
thanks very helpful, just created my own little widget.
I m also getting this type of error
Call to undefined function add_action()
please give me any solution
There’s a typo on the SELECT widget control. The lines
Should be rewritten to
Otherwise, although the correct option will be stored, the SELECT control won’t reflect the change.
Bummer, code got stripped. Anyway, these sentences:
should be
for the widget drop down control to work properly reflecting the correct option selected.
Awesome guide! Thanks a lot!
Wow! Really easy-to-read, informative guide! Able to read it, follow it and implement really quickly, thanks very much!
Quick …. must bookmark your site
!
The amount of positive feedback above is well deserved. This is a great tutorial. Thanks.
Excellent tutorial!
Thank you so much for the guide.
I had been away from the WordPress scene for a while (been doing Joomla instead) and I wasn’t aware of just how simple creating widgets now has become.
Cheers!
Hey dude, thanks for tutorial! i’m creating my own widget right now!
Thanks for a great article! I am having lots of fun playing with this tutorial.
Thanks to your post I’ve been able to create a widget to display a mini catalog. Which is working nicely.
And once again, I’ve learned a boatload from dissecting your code. Even though you don’t document it, the translation __() form was an invaluable lesson.
Now, I’d like to learn one more thing, namely how to add user controlable styling to the widget without without the user having to edit style.css so it is portable from theme to theme without having to alter the theme files.
Since there’s no HTML section, how would one go about adding CSS to the widget’s output intrinsically?
Thanks again,
Ed
Thanks…. its a realloy nice tutorial for widget …. Keep writing in such a simple maaner
Excellent guide, this was very helpful in creating a new widget for BuddyPress
Great guide, thank you. This helped me get started with wordpress widgets.
A note to anyone who is having trouble saving their widget or getting the settings to save:
I found that the $control_ops settings made my widget not save, specifically the id_base setting. Try shortening or changing your widget id_base.
I’ve written an abstract class that extend WP_Widget and speed up widget devel
http://www.strx.it/2010/11/wordpress-widgets-template/
What you think abuot it? Thanks for this guide.
Just wanted to say thank you, I used this to solve a very particular problem for a custom theme.
@Ed Tiley and others. I too needed styling for my widget and came up with this solution. I’m not sure that it’s the “correct” way to do it but it works. Put your css file in the same folder as your widget and then in your widget code add this at the top:
If anyone has suggestions to doing this better I welcome the comments. I’m writing my first widget so I know I have lot’s to learn!
PS: Justin, thanks for an excellent tutorial!
@Ed Tiley, re-reading your post I see I didn’t really answer your question with my previous post. I’m wondering if you can’t just provide the user with a text block to input their css and then just echo it out in a style block in your widget code? This is not really “standards compliant”, though it would probably work.
Okay, I’ve been searching for more articles on creating widgets with 2.8 and greater. The older widget tutorials are still too common. Good work.
Hi,
I have a problem.
When i’m trying to upload a file from the widget control, by writing HTML codes in the function form(), i’m not getting anything when i print $_FILES …..
Can anyone tell me how can i successfully use inside this class.
Any replies will be highly appreciated.
regards,
santosh
Thank you Justin,
I solved a problem for a customer with the help oft this block. I took a lot of hours, but now it looks brilliant.
Thanks a lot! Greetings from Munich!
Thorsten
Thanks Justin for the article.
Now I am novice to wordpress. Please let me know where should I copy the .php to make it appear on my admin page widget links..
Thanks in advance..
JT
Great resource!! posting it to my blog.
regards,
AJi
um… Example-Widget doesn’t remember my Gender and Display Sex settings. Always defaults to male / no.
This is without changing a thing in the download above. I’m using WP 3.0.4
Just lettin’ ya know. I would like to learn from this example though and a fix would be great. Thanks.
Nice information, thanks.
@danny
I had experiences with losing widget information. They were usually due to uppercase letters in the IDs of the sidebars. Check that first.
Then maybe is a good idea to rename the widget ID in lowercase.
I have created my first widget studying your tutorial
thanks buddy
Great post – still timely for WP 3.1.
One problem: when I add custom widgets according to the examples, it makes all of my widgets appear without any form fields in the WP widget screen, ONLY when they’re first added to widgetized area. Then, once I click the save button, the form fields appear and all is well.
Any idea what’s causing this?
It doesn’t look like there’s much activity here lately, but hopefully someone can provide an answer..
Thanks for the great post!
//Ryan
Is there any way to get widget form field value outside the widget?
Excellent. This article, the WordPress codex, and the WordPress files have greatly improved my understanding of how to build WordPress widgets.
Thank you.
This is one of the simplest tutorial for a new comer like me. I am going to convert some of my functions into widgets. as the functions have to be placed by changing code in the files.
Thank you very much for such a simple code.
Thanks for the great tutorial! I don’t understand all of it yet. But it is a big help.
First I couldn’t make it work. I copy-pasted the code into widgets.php and include_once it in my functions.php. It didn’t appear in the admin area and it broke other parts of the dashboard.
Then I changed the filename to custom-widgets.php, included it in my functions.php. And… it worked!
Just posting this for people not getting it to work either.
Thanks for this. Over two years old and still a great, straight forward, easy to follow tutorial.
It’s really great tutorial….thanku so much……keep on writing…..
Thanks for this! Helped me to wrap my head around building custom widgets. I’ve already built a couple for a client that will allow them to drop in their call-to-action widgets to their site complete with user-controlled linking for the banners. I’m also building a plugin that will house a selection of widgets for an affiliate program they are launching shortly.
Hey Justin, this is awesome. I’m in the middle of making a website for a music label and have really tried to push myself to make Wordpress into a real CMS for them. Your site has given me just about everything I need to do this, from this post to your info on custom fields and posts. Thanks so much for taking the time to provide clear, elegant examples, walkthroughs and explanations
I’m a big fan.
I need to development widget for wordpress named social-friend, I used this tutorial to learn. Thanks body.
Hi Justin,
Thx for the tutorial, really helpful. I tried to change an input line to get a textarea but when I update the content by validating it, it disappears. Could you help me here ?
Thanks !
Someone earlier had asked a question about adding a text area…so in case anyone still needs this:
basically the textarea needs a full closing tag, whereas the input tag uses the minimized tag.
So not:
but use
hey. nice tutorial. thanks for the time.
im having trouble calling a filter from a widget. is it possible. does it run too late.
function widget( $args, $instance ) {
…
add_filter( ‘the_content’, ‘filter_the_content’);
..
}
//do whatever
function filter_the_content($content) {
$bacon = ‘ bacon is good’
return $bacon . $content;
}
sorry for posting this here. but seems like you are the widget man
i was searching for the tutorial to get started with wordpress plugin development. My friend suggested me to have a look at yours. I haven’t gone anywhere else and got satisfied with the result. Cheers!! Thanks for nice tut..
Hey Justin,
I just bought the book you wrote with Brad and Ohz, and so far it is quite helpful, but the one thing that is not covered with regards to widget creation, is how to utilize multiple checkboxes that are dynamically created.
Basically I need to dynamically create a list of checkboxes, that will then be used to toggle the display of items on the frontend of the site.
I do not know how many items, or what any of their names will be.
Here’s an example from my own code I am trying to get working:
(I’ll leave out the bits that don’t apply – also please note that are supposed to represent the open and close p-h-p tags)
the last part doesn’t even matter at this point because I am unable to even get the widget to save it’s values.
I’m only about half way through your book, but am pretty certain I’m not going to find the answer since the index only lists one reference to checked() on page 70.
So how? how? HOW? do you dynamically create checkboxes in a WP Widget?
Thank you in advance for your time, effort and talent.
hmmm…
my attempt to sneak in tags didn’t work
Hello Brent,
Any luck with this multiple checkbox issue. I also have tried many way around but could not get hold of it. Would be very grateful for any leads from anybody.
Thanks you
This was perfect – I can’t believe how wasy it is to build a custom widget. Thanks.
I have developed a widget but I want to use it more than once. Is there a parameter or something that tells WP how to keep it in widgets panel while I place it on sidebar as many times as I want? Tks!
If you follow this guide, you can use the widget as many times as you want to.
Hey Nice article, however i am completely new for creating new widget, so want to know the exact file where we need to write this all widget related code.. is it in widget.php or there should be new created file?
Hi Justin,
As always your tutorials are the best….
Not sure if your still supporting questions on this old of a tutorial but I was wondering if its possible to port an image upload button into the widget such as the way the tinymce works? If so how can this be achieved?
Thanks!
heh i really wondered how can one give such a simplest steps to create widget for wp….u rock man..!!
i just created my own widget.,……thankx a lot
Thank you for this guide. It was really helpful to me a couple months ago.
I’m wondering what you think about widget classes being pluggable (using class_exists() in the same way that function_exists() is often used) as a very simple way for child theme hackers to modify a theme’s widgets. Is there anything unwise about this?
I hate pluggable functions/classes to be honest. But, as far as overwriting widgets go, you can always just extend the widget class in a child theme.
Thanks Justin. I appreciate your insight.
Many thanks Justin, this has helped me out a lot.
Hi, Can You update this tutorial so it can be use in wordpress 3.4 ?
Yep. Done.
Fantastic publish, thank you Justin! Are there any books or other tutorials you would recommend I check out to learn more?
Thanks a lot for code, this is what i was looking for..
Regards from Milap
Hi Justin,
Great article! I just wanted to know if its possible to do the same thing without using Object Oriented Programming? I am sure that there are many of us who are still new to OOP concepts & can find it really hard to follow the coding style of the current code. So if you can release a non-OOP version of the code, that would be fantastic & highly appreciated.
Thank you.
No. The old, non-OOP solution was clunky and hard to use. Trust me, I come from a procedural coding background (the few programming courses I managed to make it through in college), but OOP is much easier in this specific case.
Hey Justin. I am a total noob and know absolutely nothing but i am very interested…. can you please post a link where i can gain a bit of knowledge and understand your tutorials? Thank you in advance.
Really a good article! Ready to make my very first widget! Thank you!!!!
Thanks for the awesome tutorial! Seems it’s not so complicated after all.
Hi Justin
Thx a ton for such a wonderful tutorial. I am stuck with one problem.. That check box is not working. Humm.. it works though but not showing up checked in admin side..
Here is my code
http://pastebin.com/TTz85mFU
Can you help?
Regards
Perfect !!
Thanks master for the tutorials… You really help me…,,
The very next time I read a blog, I hope that it does not disappoint me just as much as this particular one. I mean, Yes, it was my choice to read, but I really believed you would have something helpful to talk about. All I hear is a bunch of complaining about something that you can fix if you were not too busy searching for attention.
Such simple widget, but it requires more than one hundred lines of php code. From your tutorial it is easier to understand how to create a widget than from wordpress help documents.