Advanced widgets. Widgets with controls.
Posted by Leonid Mamchenkov on June 17, 2007
Hopefully, by now you understand how cool and powerful WordPress widgets are. Widgets 101 demonstrated how to create simple widgets with text paragraphs, HTML markup, and even some PHP code. What else is there? Not much, but something.
In this post we’ll take a look at how to create widgets which support options and easy configuration via administration interface. WordPress calls these widgets with controls.
Let’s reuse one of the examples from the Simple Widgets post – the Date widget. Here is how it looks so far, without any controls.
We have all output in widgets/current_date.php file:
And we have registered this widget in functions.php file of our theme like so:
It works and seem OK, doesn’t it? Well, it does. But what if we want to change the format of the date? What if instead of “February 23, 2007” we want to use “23 Feb 2007”? We’ll have to edit the file widgets/current_date.php and correct the date() format. This doesn’t seem right. WordPress is a beautiful, flexible platform, and we shouldn’t be editing PHP files for simple changes like that.
And, indeed, we don’t have to. Let’s upgrade this widget. We’ll give it a control – a configuration screen, where users will be able to edit date() formats. For this to work, we’ll have to do the following:
- Upgrade our output function to understand options.
- Create a new function which will manage option editing.
- Register that new option editing function as widget control.
Here is how the new function for date printing looks:
All in all, it is very similar to what we had before. The core functionality of this widget is still date printing. Now, for our control function:
Of course, you can have several options in there, text paragraphs with option descriptions, images with instructions, and so on. Play with it. Try new things out. By the way, this code above was adopted from the WordPress’ core code for default widgets.
We have all the pieces now. It’s time to put them all together. I mean, we should proceed to step 3 of the list above and register the control for the widget. Here is how both widget and widget control are registered in my functions.php file:
In the administration interface, where I drag-and-drop the widgets, I now have a box called ‘Date’. When I drop it into one of my widget containers, I see that my ‘Date’ box also has an icon. When I click on the icon, a small window pops up, which asks me for date() format.
Now you know all about WordPress widgets that there is to know. Enjoy.