201 Responses

  1. The Frosty @WPCult
    The Frosty @WPCult May 27, 2009 at 1:00 am | | Reply

    I’m going to have to read that again when I am not so tired..

    Good write up.

  2. Stefano
    Stefano May 27, 2009 at 2:53 am | | Reply

    As usual, Justin: great great article!

    Stefano

  3. Dicas, Dicas e mais Dicas | pBlog May 27, 2009 at 8:17 am |
  4. J Mehmett
    J Mehmett May 27, 2009 at 8:22 am | | Reply

    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.

  5. Good Guide for creating Widgets May 27, 2009 at 8:57 am |
  6. Randa Clay
    Randa Clay May 27, 2009 at 3:52 pm | | Reply

    As always Justin, you rock. I’m mildly techie, but I think with your excellent instructions I could do this!

  7. Matt
    Matt May 28, 2009 at 12:14 am | | Reply

    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.

  8. Matt
    Matt May 30, 2009 at 2:34 pm | | Reply

    @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_STRING

  9. Matt
    Matt May 30, 2009 at 8:27 pm | | Reply

    Thanks for the link Justin, I got it to work.

  10. links for 2009-06-03 « sySolution June 3, 2009 at 10:01 am |
  11. chantelle tamaris
    chantelle tamaris June 3, 2009 at 10:37 am | | Reply

    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!

  12. leon
    leon June 7, 2009 at 1:46 pm | | Reply

    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

  13. Jennifer
    Jennifer June 11, 2009 at 10:06 pm | | Reply

    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… :)

  14. Jennifer
    Jennifer June 12, 2009 at 8:46 am | | Reply

    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.

  15. Mikko
    Mikko June 12, 2009 at 11:02 pm | | Reply

    Excellent and easy tutorial. Thanks a lot!

  16. Mikko
    Mikko June 13, 2009 at 5:13 am | | Reply

    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?

  17. George Serradinho
    George Serradinho June 14, 2009 at 12:42 pm | | Reply

    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 :)

  18. Max
    Max June 15, 2009 at 11:04 pm | | Reply

    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!

  19. Vasudevbbhat
    Vasudevbbhat June 16, 2009 at 5:47 am | | Reply

    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

  20. Nimesh Kumar
    Nimesh Kumar June 16, 2009 at 5:58 am | | Reply

    Thanks

    Great Stuff !!!!!!!!!!!!

    There is nothing getting stuck at any point……….
    I have created lot of widgets using this one structure…….

  21. Jon Pruett
    Jon Pruett June 16, 2009 at 2:26 pm | | Reply

    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!

  22. Mark
    Mark June 18, 2009 at 8:15 am | | Reply

    Thanks Justin. This was a nice little tute to get me fast-tracked onto making some custom WP 2.8 widgets.

    Cheers!

  23. smsfame.com
    smsfame.com June 19, 2009 at 2:30 am | | Reply

    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?

  24. Edgar Doiron
    Edgar Doiron June 22, 2009 at 12:41 pm | | Reply

    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?

  25. P.Raman
    P.Raman July 1, 2009 at 5:37 am | | Reply

    Hi

    Please tell me how to create a drop-down author list widget, similar to categories widget.

    Thank you.

  26. Stéphane Gallay
    Stéphane Gallay July 16, 2009 at 4:17 am | | Reply

    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?

  27. Ditutu
    Ditutu July 16, 2009 at 12:54 pm | | Reply

    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 .

  28. Edgar Doiron
    Edgar Doiron July 16, 2009 at 8:06 pm | | Reply

    @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?

  29. Johnny Goodperson
    Johnny Goodperson July 21, 2009 at 4:42 am | | Reply

    Thanks for your tutor mate :)
    i’ll make it :D

  30. Joe Random
    Joe Random July 22, 2009 at 8:51 am | | Reply

    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

  31. Joe Random
    Joe Random July 22, 2009 at 8:52 am | | Reply

    Sorry, one more time- why you’ve not added any ads?

  32. Kevin Baker
    Kevin Baker July 24, 2009 at 9:55 am | | Reply

    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

  33. JNFerree
    JNFerree July 24, 2009 at 10:13 am | | Reply

    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?

  34. links for 2009-07-24 » 4exp.net July 24, 2009 at 12:07 pm |
  35. Joe Somebody
    Joe Somebody July 27, 2009 at 12:44 am | | Reply

    Excellent guide to start with wordpress . At firt i feel so tired . Nowwith this tutorial everything is clear .

  36. cas
    cas July 28, 2009 at 4:33 pm | | Reply

    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 –

    /* Display name from widget settings. */
    		if ( $name )
    			echo 'Hello.  My name is' . $name . '.';
    /* Display name from widget settings if one was input. */
    		if ( $name )
    			printf( __('Hello.  My name is %1$s', 'example'), $name );

    What is the difference between using echo and printf (besides printf using more code)?

  37. Laura
    Laura July 28, 2009 at 6:25 pm | | Reply

    Justin, many thanks for the tutorial – I looked a lot to find how to do this.

  38. Jane Doe
    Jane Doe July 29, 2009 at 8:23 pm | | Reply

    Great and complete tutorial Justin,like always thank you!

  39. GTRway
    GTRway July 30, 2009 at 2:33 am | | Reply

    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?

  40. cas
    cas July 30, 2009 at 8:56 am | | Reply

    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! :)

  41. Jeff @ Code Research Center
    Jeff @ Code Research Center August 2, 2009 at 7:22 pm | | Reply

    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.

  42. Adam
    Adam August 5, 2009 at 2:56 am | | Reply

    Very good tutorial for me as a newbee.
    I wonder is there any program or plugin to make widget in wordpress?.

  43. Adz
    Adz August 5, 2009 at 11:07 pm | | Reply

    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

  44. Gaurav
    Gaurav August 6, 2009 at 7:04 am | | Reply

    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

  45. Gaurav
    Gaurav August 7, 2009 at 6:49 am | | Reply

    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.

  46. Gunjan
    Gunjan August 10, 2009 at 2:34 am | | Reply

    Gr8 stuff….will surly try it out…..sweet and simple

  47. Sarah
    Sarah August 11, 2009 at 7:24 am | | Reply

    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.

  48. Links for August 11th August 11, 2009 at 8:30 am |
  49. Trabajo
    Trabajo August 23, 2009 at 10:24 pm | | Reply

    Very good tutorial for me, I wonder is there any program or plugin to make widgets for wordpress blogging platform.

  50. Webdesigner
    Webdesigner August 26, 2009 at 9:06 am | | Reply

    Wow, thanx for this tutorial! I can’t wait to get my hands on this at evening!

  51. willsy
    willsy August 30, 2009 at 3:14 pm | | Reply

    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 ?

  52. Raymond
    Raymond September 2, 2009 at 11:02 pm | | Reply

    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.

  53. Edward Caissie
    Edward Caissie September 3, 2009 at 2:57 pm | | Reply

    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!

  54. World of Wordpress at Helpful Technology September 21, 2009 at 4:39 pm |
  55. Len
    Len October 1, 2009 at 4:00 pm | | Reply

    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

  56. Dustin Dempsey
    Dustin Dempsey October 26, 2009 at 8:56 pm | | Reply

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

  57. Darshana Gunawardana
    Darshana Gunawardana November 1, 2009 at 9:28 pm | | Reply

    This is great. Specially very good tutorial for me.
    Thanks….

  58. elliot condon
    elliot condon November 22, 2009 at 11:04 pm | | Reply

    great tutorial. The new way of making widgets makes a lot of sense coming from a programming background

  59. amber
    amber November 23, 2009 at 3:54 pm | | Reply

    your download link appears to be broken.

  60. neha
    neha December 8, 2009 at 2:45 am | | Reply

    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!

  61. Tom
    Tom December 9, 2009 at 6:27 pm | | Reply

    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

  62. beep
    beep December 17, 2009 at 4:27 pm | | Reply

    clear explanation…Had some issues but all ok now

    regards

  63. andre
    andre December 25, 2009 at 11:06 pm | | Reply

    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

  64. Sébastien Méric
    Sébastien Méric December 28, 2009 at 12:39 pm | | Reply

    Hi,

    It seems that there was a modification of the __checked_selected_helper function (wp-admin/includes/template.php) in wp 2.9. The if ( $helper == $current) test as been replaced with if ( (string) $helper === (string) $current) test so the checked( $instance['show_sex'], true ) doesn’t work anymore ! I think that you will have to replace it with checked( $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.

    1. adrian
      adrian November 10, 2011 at 5:16 pm | | Reply

      yes. i believe that is true. urgh

      1. adrian
        adrian November 10, 2011 at 5:24 pm |

        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

  65. CoreBloggers January 4, 2010 at 7:35 am |
  66. Rick Falkvinge
    Rick Falkvinge January 9, 2010 at 3:41 pm | | Reply

    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.

  67. Fairweb
    Fairweb January 16, 2010 at 8:02 am | | Reply

    Great guide Justin ! Thanks !

  68. Brian
    Brian January 20, 2010 at 12:23 am | | Reply

    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?

  69. Rupak
    Rupak February 1, 2010 at 5:27 am | | Reply

    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!!

  70. Paul
    Paul February 3, 2010 at 7:14 pm | | Reply

    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.

  71. virg
    virg February 6, 2010 at 1:17 am | | Reply

    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.

  72. Mike Smith
    Mike Smith February 11, 2010 at 7:49 pm | | Reply

    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 :)

  73. Mike Smith
    Mike Smith February 11, 2010 at 10:33 pm | | Reply

    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.

    1. frq
      frq February 12, 2010 at 9:28 pm | | Reply

      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.

  74. frq
    frq February 12, 2010 at 9:20 pm | | Reply

    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:

    $instance['show_sex'] = $new_instance['show_sex'];

    to:

    $instance['show_sex'] = isset($new_instance['show_sex']);

    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 ;-)

  75. frq
    frq February 12, 2010 at 9:24 pm | | Reply

    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:

    checked( $instance['show_sex'], true );

    to:

    checked(isset( $instance['show_sex']) ? $instance['show_sex'] : 0  );

    frq.

  76. dandy
    dandy March 23, 2010 at 7:42 am | | Reply

    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.

  77. dandy
    dandy March 23, 2010 at 9:24 am | | Reply

    i fixed it by replacing
    $instance['format']

    with
    $instance['sex'] in selectbox drop down.

    Thanks.

  78. dandy
    dandy March 23, 2010 at 10:53 am | | Reply

    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.

  79. Owen Hoskins
    Owen Hoskins March 23, 2010 at 2:43 pm | | Reply

    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

  80. Lee
    Lee March 26, 2010 at 11:08 am | | Reply

    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?

  81. Joey Novak
    Joey Novak March 30, 2010 at 4:01 pm | | Reply

    Awesome Post! Just what I needed. Extremely Clear and concise.

    Thanks!

  82. Johnathan Andersen
    Johnathan Andersen April 11, 2010 at 3:38 am | | Reply

    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.

  83. Monpelaud
    Monpelaud April 19, 2010 at 7:14 am | | Reply

    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

  84. Carla
    Carla April 20, 2010 at 8:12 am | | Reply

    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

  85. Yvonne
    Yvonne May 2, 2010 at 3:05 am | | Reply

    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.

  86. Robert Heller
    Robert Heller May 16, 2010 at 2:05 pm | | Reply

    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.

    Here is the code:
    /* Add our function to the widgets_init hook. */
    add_action( 'widgets_init', 'load_deepwoods_GAN_Widget' );
    
    /* Function that registers our widget. */
    function load_deepwoods_GAN_Widget() {
    	register_widget( 'Deepwoods_GAN_Widget' );
    }
    
    class Deepwoods_GAN_Widget extends WP_Widget {
    
      function Deepwoods_GAN_Widget() {
        /* Widget settings. */
        $widget_ops = array( 'classname' => 'deepwoods_gan_widget', 'description' => __('Display GAN links', 'ganads') );
    
        /* Widget control settings. */
        $control_ops = array( 'width' => 200, 'height' => 150, 'id_base' => 'deepwoods_GAN' );
    
        /* Create the widget. */
        $this->WP_Widget( 'deepwoods-gan-widget', __('GAN Ads', 'ganads') , $widget_ops, $control_ops );
      }
    
      function widget ($args, $instance) {
        extract($args);
        echo $before_widget;
        //echo $before_title . $after_title;
        global $wpdb;
        $GANAds = $wpdb->get_results("SELECT * FROM " . DEEPWOODS_GAN_TABLE, 'ARRAY_A');
    
        if (! empty($GANAds) ) {
          echo '';
          $testside = $instance['ulid'] == 'GANright';
          foreach ((array)$GANAds as $GANAd) {
            //if ( $GANAd['StartDate'] > today && $GANAd['EndDate'] < today ) continue;
    	if ( $GANAd['side'] == $testside) {
    	  echo '<a href="' . $GANAd['ClickserverLink'] . '" rel="nofollow">' . $GANAd['LinkName'] . '</a>' . $GANAd['MerchandisingText'] . '';
    	}
          }
          ?> 'GANright' );
        $instance = wp_parse_args( (array) $instance, $defaults ); ?>
    
    	<label for="get_field_id( 'ulid' ); ?>">Side:
    	<select id="get_field_id( 'ulid' ); ?>" name="get_field_name( 'ulid' ); ?>" class="widefat" style="width:100%;">
    	    <option >right
    	    <option >leader
    
        prefix . "DWS_GAN");
    function deepwoods_make_GAN_table () {
      $columns = array ( 'id' => 'int NOT NULL AUTO_INCREMENT',
    		     'Advertiser' => 'varchar(255) NOT NULL' ,
    		     'LinkID'     => 'varchar(16)  NOT NULL' ,
    		     'LinkName'   => 'varchar(255) NOT NULL' ,
    		     'MerchandisingText' => 'varchar(255)' ,
    		     'AltText' => 'varchar(255)' ,
    		     'StartDate' => 'date NOT NULL' ,
    		     'EndDate'   => 'date NOT NULL' ,
    		     'ClickserverLink' => 'varchar(255) NOT NULL' ,
    		     'ImageURL' => 'varchar(255)' ,
    		     'ImageHeight' => 'varchar(255)' ,
    		     'ImageWidth' => 'varchar(255)' ,
    		     'LinkURL' => 'varchar(255) NOT NULL' ,
    		     'PromoType' => 'varchar(32) NOT NULL' ,
    		     'MerchantID'  => 'varchar(16) NOT NULL',
    		     'side' => 'boolean NOT NULL',
    		     'PRIMARY' => 'KEY (id)'
    		   );
       global $wpdb;
       $sql = "CREATE TABLE " . DEEPWOODS_GAN_TABLE . '(';
       foreach($columns as $column => $option) {
    	$sql .= "{$column} {$option}, ";
       }
       $sql = rtrim($sql, ', ') . ")";
       if($wpdb->get_var("SHOW TABLES LIKE '" . DEEPWOODS_GAN_TABLE . "'") != DEEPWOODS_GAN_TABLE) {
    	require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    	dbDelta($sql);
       }
    }
    
    deepwoods_make_GAN_table();
  87. Robert Heller
    Robert Heller May 16, 2010 at 4:47 pm | | Reply

    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.

    1. Robert Heller
      Robert Heller May 17, 2010 at 9:14 am | | Reply

      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.

  88. David Siegfried
    David Siegfried May 24, 2010 at 11:44 pm | | Reply

    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.

  89. Ken Kennedy
    Ken Kennedy May 30, 2010 at 7:16 pm | | Reply

    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?

  90. Ken Kennedy
    Ken Kennedy May 30, 2010 at 7:29 pm | | Reply

    Well, to answer my own question, since I’m using WordPress MU, it apparently has to go under the mu-plugins directory.

  91. Dineshkumar
    Dineshkumar June 28, 2010 at 5:14 am | | Reply

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

  92. Dineshkumar
    Dineshkumar July 1, 2010 at 4:06 am | | Reply

    Can one tell “where the widget data is stored in Database”?

    1. Eleven
      Eleven July 13, 2010 at 6:09 pm | | Reply

      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?

  93. meilione
    meilione July 8, 2010 at 10:22 am | | Reply

    thanks very helpful, just created my own little widget.

  94. Gaurav
    Gaurav July 21, 2010 at 5:52 am | | Reply

    I m also getting this type of error

    Call to undefined function add_action()

    please give me any solution

  95. Elio
    Elio July 22, 2010 at 4:01 pm | | Reply

    There’s a typo on the SELECT widget control. The lines

    <option >male
    <option >female

    Should be rewritten to

    <option >male
    <option >female

    Otherwise, although the correct option will be stored, the SELECT control won’t reflect the change.

  96. Elio
    Elio July 22, 2010 at 4:03 pm | | Reply

    Bummer, code got stripped. Anyway, these sentences:

    'male' == $instance['format']
    'female' == $instance['format']

    should be

    'male' == $instance['sex']
    'female' == $instance['sex']

    for the widget drop down control to work properly reflecting the correct option selected.

  97. Sebastian
    Sebastian August 14, 2010 at 12:09 pm | | Reply

    Awesome guide! Thanks a lot!

  98. Josh
    Josh August 23, 2010 at 2:17 pm | | Reply

    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 ;) !

  99. Ben Jackson
    Ben Jackson September 10, 2010 at 6:56 am | | Reply

    The amount of positive feedback above is well deserved. This is a great tutorial. Thanks.

  100. Sana
    Sana September 18, 2010 at 10:58 pm | | Reply

    Excellent tutorial!

  101. Rafael Minuesa
    Rafael Minuesa September 22, 2010 at 12:36 am | | Reply

    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!

  102. Drakezilla
    Drakezilla September 24, 2010 at 8:59 am | | Reply

    Hey dude, thanks for tutorial! i’m creating my own widget right now! :D

  103. Josh
    Josh September 27, 2010 at 11:03 pm | | Reply

    Thanks for a great article! I am having lots of fun playing with this tutorial.

  104. Ed Tiley
    Ed Tiley October 4, 2010 at 3:26 pm | | Reply

    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

  105. ashish
    ashish October 11, 2010 at 3:43 am | | Reply

    Thanks…. its a realloy nice tutorial for widget …. Keep writing in such a simple maaner :)

  106. Chad Huntley
    Chad Huntley October 27, 2010 at 3:44 pm | | Reply

    Excellent guide, this was very helpful in creating a new widget for BuddyPress

  107. Leslie
    Leslie November 1, 2010 at 8:48 am | | Reply

    Great guide, thank you. This helped me get started with wordpress widgets.

  108. Luke
    Luke November 8, 2010 at 11:37 am | | Reply

    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.

  109. Francesco
    Francesco November 12, 2010 at 2:01 am | | Reply

    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.

  110. Steve Lambert
    Steve Lambert November 21, 2010 at 10:57 pm | | Reply

    Just wanted to say thank you, I used this to solve a very particular problem for a custom theme.

  111. teebee
    teebee November 24, 2010 at 9:10 am | | Reply

    @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:

    add_action( 'widgets_init', 'init_my_widget' );
    
    And then added this function:
    function init_my_widget() {
    		/* Load our stylesheet. */
    		wp_enqueue_style('My_Widget_Stylesheet', WP_PLUGIN_URL . '/my_plugin_dir/my-plugin.css');
     }

    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!

  112. teebee
    teebee November 24, 2010 at 9:47 am | | Reply

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

  113. DavidM
    DavidM December 19, 2010 at 4:28 am | | Reply

    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.

  114. Santosh kumar sahoo
    Santosh kumar sahoo December 30, 2010 at 12:40 am | | Reply

    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

  115. Thomas Willers
    Thomas Willers January 1, 2011 at 6:06 am | | Reply

    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

  116. JT
    JT January 1, 2011 at 7:21 pm | | Reply

    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

  117. AJi Prabowo
    AJi Prabowo January 25, 2011 at 5:41 am | | Reply

    Great resource!! posting it to my blog.

    regards,
    AJi

  118. danny
    danny February 17, 2011 at 1:44 pm | | Reply

    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.

  119. Richard Vencu
    Richard Vencu February 22, 2011 at 5:43 am | | Reply

    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.

  120. Amit
    Amit February 23, 2011 at 1:26 am | | Reply

    I have created my first widget studying your tutorial :D thanks buddy

  121. Ryan
    Ryan March 10, 2011 at 7:39 pm | | Reply

    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

  122. kuldeep
    kuldeep March 16, 2011 at 4:55 am | | Reply

    Is there any way to get widget form field value outside the widget?

  123. Brent Lineberry
    Brent Lineberry May 5, 2011 at 9:46 pm | | Reply

    Excellent. This article, the WordPress codex, and the WordPress files have greatly improved my understanding of how to build WordPress widgets.

    Thank you.

  124. rakesh kumar
    rakesh kumar May 6, 2011 at 11:27 pm | | Reply

    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.

  125. Jelle
    Jelle May 10, 2011 at 3:03 pm | | Reply

    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.

  126. Jon
    Jon June 11, 2011 at 2:27 am | | Reply

    Thanks for this. Over two years old and still a great, straight forward, easy to follow tutorial.

  127. Mehak Gupta
    Mehak Gupta June 22, 2011 at 11:54 am | | Reply

    It’s really great tutorial….thanku so much……keep on writing…..

  128. Ashton
    Ashton June 24, 2011 at 11:47 am | | Reply

    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.

  129. Melanie
    Melanie August 12, 2011 at 5:17 pm | | Reply

    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.

  130. Kedar Sapkota
    Kedar Sapkota October 12, 2011 at 2:38 am | | Reply

    I need to development widget for wordpress named social-friend, I used this tutorial to learn. Thanks body.

  131. Francis
    Francis October 19, 2011 at 3:17 pm | | Reply

    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 ! ;-)

  132. adrian
    adrian November 10, 2011 at 7:36 pm | | Reply

    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

  133. Joe
    Joe November 15, 2011 at 5:34 am | | Reply

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

  134. brent
    brent November 15, 2011 at 8:12 pm | | Reply

    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)

    function form( $instance ) {
    
    	$instance = wp_parse_args( (array) $instance, $defaults );
    
    	echo ''.__('Display the following:', 'my_plugin');
    	echo '';
    
    	foreach ( $items as $item_type => $item ) {
    
    		$label = isset( $item['title'] ) ? $item['title'] : $item_type ;
    
    		$chk = 'item_display_' . $item_type;
    
    		<input type="checkbox"
    			name=" echo $this->get_field_name( $chk );"
    			value=" echo $instance[$chk];"
    			 echo checked( $instance[$chk], TRUE );/>
    
    		 echo __($label, 'my_plugin');?>
    	}
    
    	echo '';
    
    }
    
    function update( $new_instance, $old_instance ) {
    
    	$instance = $old_instance;
    	$instance['title'] = strip_tags( $new_instance['title'] );
    
    	foreach ( items as $item_type => $item ) {
    
    		$chk = 'item_display_' . $item_type;
    		$instance[$chk] = strip_tags( $new_instance[$chk] );
    
    	}
    
    	return $instance;
    }
    
    function widget( $args, $instance ) {
    
    	extract($args);
    
    	foreach ( items as $item_type => $item ) {
    
    		$chk = 'item_display_' . $item_type;
    
    		if ( $instance[$chk] == TRUE ) {
    		// display item
    		}
    	}
    }

    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.

  135. brent
    brent November 15, 2011 at 8:14 pm | | Reply

    hmmm…

    my attempt to sneak in tags didn’t work

    1. Sanam Maharjan
      Sanam Maharjan December 2, 2011 at 1:54 am | | Reply

      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 :)

  136. James
    James November 16, 2011 at 7:49 am | | Reply

    This was perfect – I can’t believe how wasy it is to build a custom widget. Thanks.

  137. Wordpress Widgets « netzdings.de December 5, 2011 at 5:46 pm |
  138. Edson
    Edson December 17, 2011 at 4:20 pm | | Reply

    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!

  139. Matty
    Matty February 17, 2012 at 7:04 am | | Reply

    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?

  140. Shaun
    Shaun April 25, 2012 at 11:48 pm | | Reply

    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!

Leave a Reply

By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution.

Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.