One of the main changes in WordPress 2.8 is the new widget API. This API is fully object oriented and provides the programmer all the necessary functions to create a WordPress widgets. Also, it now allows multiple use of each widget.
You can find the widget API in wp-includes/widget.php and the widgets itself in wp-includes/default-widgets.php. The class WP_Widget provides the functionality of the widgets, and each widget must be inherited. The class WP_Widget_Factory is for registration and instantiation of widgets responsible.
How to create a widget in WordPress 2.8?
It will be a simple example and will output the links for the RSS Feed of the articles and comments. In functions.php we first create the skeleton of our widgets:
class My_RSS_Widget extends WP_Widget {
function My_RSS_Widget() {
//Constructor
}
function widget($args, $instance) {
// prints the widget
}
function update($new_instance, $old_instance) {
//save the widget
}
function form($instance) {
//widgetform in backend
}
}
register_widget('My_RSS_Widget');
We have a class My_RSS_Widget created, which inherits the properties and methods of the WP_Widget class (extends). In a new widget, the methods widget and update always have to be created, form is optional. With register_widget ( ‘My_RSS_Widget’) will be the widget registered. Let’s fill up our widget.
class My_RSS_Widget extends WP_Widget {
function My_RSS_Widget() {
$widget_ops = array('classname' => 'widget_rss_links', 'description' => 'A list with your feeds links' );
$this->WP_Widget('rss_links', 'Feed links', $widget_ops);
}
function widget($args, $instance) {
extract($args, EXTR_SKIP);
echo $before_widget;
$title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);
$entry_title = empty($instance['entry_title']) ? ' ' : apply_filters('widget_entry_title', $instance['entry_title']);
$comments_title = empty($instance['comments_title']) ? ' ' : apply_filters('widget_comments_title', $instance['comments_title']);
if ( !empty( $title ) ) { echo $before_title . $title . $after_title; };
echo '<ul id="rss">';
echo ' <li><a href=" ' . get_bloginfo('rss2_url') . '" rel="nofollow" title=" ' . $entry_title . ' ">' . $entry_title . '</a></li>';
echo ' <li><a href=" ' . get_bloginfo('comments_rss2_url') . '" rel="nofollow" title=" '. $comments_title . ' ">' . $comments_title . '</a></li>';
echo '</ul>';
echo $after_widget;
}
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['entry_title'] = strip_tags($new_instance['entry_title']);
$instance['comments_title'] = strip_tags($new_instance['comments_title']);
return $instance;
}
function form($instance) {
$instance = wp_parse_args( (array) $instance, array( 'title' => '', 'entry_title' => '', 'comments_title' => '' ) );
$title = strip_tags($instance['title']);
$entry_title = strip_tags($instance['entry_title']);
$comments_title = strip_tags($instance['comments_title']);
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('entry_title'); ?>">Title for entry feed: <input class="widefat" id="<?php echo $this->get_field_id('entry_title'); ?>" name="<?php echo $this->get_field_name('entry_title'); ?>" type="text" value="<?php echo attribute_escape($entry_title); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('comments_title'); ?>">Title for comments feed: <input class="widefat" id="<?php echo $this->get_field_id('comments_title'); ?>" name="<?php echo $this->get_field_name('comments_title'); ?>" type="text" value="<?php echo attribute_escape($comments_title); ?>" /></label></p>
<?php
}
}
register_widget('My_RSS_Widget');
The widget feature is for the output in the frontend to examine the update data and stores an instance of the widget and form creates in the backend the input mask, which in our case for the title of the widget and the displayed link text.
The code is self-explanatory. The function widget is for the output in the frontend responsible, update examine the data and stores an instance of the widget and form creates in the backend the input mask, which in our case for the title of the widget and the displayed link text.
So now implement your own ideas!
Please check out the post WordPress 2.8 Single Post Navigation Widget for a more advanced example.
Comments
54 responses to “Build A WordPress 2.8 Widget With The New Widget API”
[…] 2.8 incorpora como novedad una nueva API para Widgets muy, pero que muy interesante. La gente de WP-Engineer.com nos muestran un avance de lo que será desarrollar usando esta nueva […]
This is a great news. The old widget implemetation just didn’t seem very well thought out, and it was pretty hard to use, especially if you wanted multiple instances of your widget. This is going to make things much better for everyone.
Is there any backwards compatibility with this built into 2.8? While it is great news moving forward, there could be a lot of incompatible plugins for a while.
[…] Michael Preuss (WP Engineer) zeigt wie man Widgets mit der neuen Widget API erstellt. Link […]
Peter,
I’ve created a tool that lets you wrap some php code in either the new 2.8 style widget or the existing widget style so it should be pretty easy to make a version for existing site as well as new sites. Please check out the tool at widgetifyr.com. Let me know how it works for you.
Glenn
[…] Build A WordPress 2.8 Widget With The New Widget API – One of the main changes in WordPress 2.8 is the new widget API. This API is fully object oriented and provides the programmer all the necess… […]
[…] yet had a chance to see how the new widgets are created I recommend you take a quite read of Build a WordPress 2.8 Widget over at Wp Engineer. I think you will agree that it is pretty […]
Very helpful articles, I’ve a theme with multiple sidebar so 2.8 new widgets API will have it used.
Cheers & thanks
[…] a look at wp-includes/widgets.php, you’ll be thrilled to dicover that wp 2.8 will let you create your own widgets and use them in multiple instances on the same page (i.e. WordPress won’t provide an unique […]
[…] Build A WordPress 2.8 Widget – WP Engineer […]
[…] Build A WordPress 2.8 Widget With The New Widget API widget API, widget, update, form, registerwidget, widget – from WP Engineer (tags: wordpress api programming plugins development tutorial widgets 2009-06 cms blogging) […]
[…] Build A WordPress 2.8 Widget […]
Looks quite simple. Should be alot easier to create custom widgets now instead of hacking things together with the text widget.
Thanks for the tutorial.
[…] Build A WordPress 2.8 Widget – WP Engineer […]
[…] Build A WordPress 2.8 Widget – WP Engineer […]
great ,
[…] Build A WordPress 2.8 Widget With The New Widget API […]
@Peter, backwards compatibility seems ok so far for all the widgets I’ve used.
@Jonathan – What about widgets coded using the new Widgets API working in previous versions? If I code a widget for 2.8, will it work in 2.7?
@Zack: No! That produces a fatal error. The classes doesn’t exist.
@Michael – That’s what I figured. Is there a way that we can include the class in the widget download and say in PHP if class does not exist, include this file — or is the code more spread out than 1 file?
I see it’s in wp-includes/widgets.php. Would code work like this:
<?php if (!class_exists('WP_Widget')) {
include('/path/to/class/wp-content/plugins/this-widget/widgets.php');
} ?>
I assume that would work….any reason why not?
Not tested:
[…] Build a WordPress 2.8 Widget with New Widget API – WPEngineer […]
@Michael: your snippet works as expected.
There’s a typo in the code above: inside the My_RSS_Widget class, line 10 inside the widget function – “wp $entry_title” should be “$entry_title”.
Anyway, thanks for the great post!
Thanks Christian! Fixed.
Can you please tell me how to create a widget to show a drop-down list of authors in a multi-author blog using the WP 2.8 widget API.
I find that the default widgets have categories list but not author list.
Thanks
@P.Raman: Nice idea. But it isn’t done in five minutes.
How would I call that function” function widget($args, $instance) ” ?
in 2.5ish it was easy just to do and it would execute the function.
[…] einem einfachen Beipiel beschrieben, wie man ein Widget programmiert. Dieser Beitrag ist auch auf WP Engineer erschienen und ist dort einer der erfolgreichsten Artikel. Diesmal habe ich mir etwas komplexeres […]
You don’t have to call widget(). WordPress does it for you if the widget is active.
That’s not what I asked, read it again.
I figured it out, my actual code execution that I would place inside the function widget() area I actually have *above* the class and called by function widget() {} .. call it My_RSS(){ ..
Now if I go and hardcode it on the site someplace I can do that.
– Phil
HI!
Nice tut! But, i have a question. When i try to make a plugin by the above code, the WP has dropped an error, such as “register is not a member class” or something else like this…
So how can i make a widget by the API in a plugin file? I have to use add_action() ot register_widget_controller() or what?
Thanks for the help!
TZS
TZS,
with a plugin you can use
tyvm! it works.
Not sure what I am doing wrong but I get this error:
Warning: Missing argument 2 for WP_Widget::__construct(), called in \wp-includes\widgets.php on line 320 and defined in\wp-includes\widgets.php on line 93
Great article by the way !
[…] Build A WordPress 2.8 Widget – WP Engineer […]
[…] thanks to WPengineer for the code to this, which I modified […]
[…] Build a WordPress WidgetI’m starting to get the hang of this Widget thing 05 Sep 2009 […]
If you get “Missing argument 2 for WP_Widget::__construct(), ” make sure that you when you renamed your widget class that extends WP_Widget(), to name the function with the ops to same thing.
[…] Panels in WordPress10 incredibly cool WordPress shortcodesAn Introduction to WordPress Action HooksBuild A WordPress 2.8 Widget With The New Widget APISom du ser här ovan så delar jag med mig av 8 webbplatser (länkar), vill du ta del av alla tips […]
If you run into problems like:
PHP Fatal error: Call to a member function register() on a non-object in ../wp-includes/widgets.php
You may need to adjust your registration code to wait until the WordPress init is completed, like this:
function register_My_RSS_Widget(){
register_widget(‘My_RSS_Widget’);
}
add_action(‘init’, ‘register_My_RSS_Widget’, 1)
[…] based on WordPress 2.6, however in the current 2.8.5 widgets are designed using the new widget API, https://wpengineer.com/wordpress-built-a-widget/ so I’m going to leave that for another […]
[…] только с WordPress 2.8 и выше, так как используется новый Widget API. <?php class wpe_comment_widget extends WP_Widget { function wpe_comment_widget() { […]
amazing!!
thanks so much.
I also had an error like TZS
and replacing:
register_widget(‘My_RSS_Widget’);
with:
add_action( ‘widgets_init’, create_function(”, ‘return register_widget(“My_RSS_Widget”);’) );
workd masterfully THANKS!
[…] Some good examples are available at: https://wpengineer.com/wordpress-built-a-widget/ […]
[…] neat posts: Build a WordPress 2.8 Widget With the New Widget API Exclude a Category From “Turn Off Comments” Automatically. Display the Total Number of […]
I had the same problem as Ron. This tutorial aslo explains it quite well:
http://justintadlock.com/archives/2009/05/26/the-complete-guide-to-creating-widgets-in-wordpress-28
[…] Build A WordPress 2.8 Widget With The New Widget API (WPEngineer) […]
Good introduction to the new widget class Michael.
Just a tip: You can replace the code in the update method with this:
$instance = array_merge($old_instance, $new_instance)
return array_map(‘strip_tags’, $instance);
This way it’s less lines of code and you don’t need to add code when you add new settings.
Great article!
I read many articles on this subject, but yours is first that mentioned where widget code should be placed. Thank you for that! I started freaking out. Like it’s so obvious to beginner that it should go to functions.php.
[…] Vielen Dank an dieser Stelle für den Hinweis von Michael und die hilfreiche Beschreibung »Build a WordPress 2.8 Widget with the New Widget API« auf […]
@Sitebaes:
Wow, that’s a wicked replacement.
What about the widget form? Is there a simpler way you might advise for handling creating the form elements for the widget options?
i try this in my function.php,works fine ,except sidebar widget panel cannot be draggable anymore.do someone know why?thank you.