in CMS

How to create a wordpress widget?

WordPress widgets are extremly useful blocks that bloggers or web administrators can use to enhance the functionality of their wordpress site. A widget is a block that performs a unique task. It can be either a block that shows the recently added posts to your blog or it can be a simple widget that just contains a few social networking  links.

In this tutorial, I will explain the step by step procedure to create a new widget.

To keep a simple flow, I am going to create a widget for my plugin WP-Multiratings which allows people to rate the wordpress posts.  This widget will display top n most rated or least rated posts for a particular rating type.

The simplest method of creating a wordpress widget to create a separate file that stores our wordpress widget code.

Step 1

Create a file wpmrwidget.php and create a class WpmrWidget in it. This class inherits the base wordpress WP_Widget class.

<?php
class WpmrWidget extends WP_Widget {
function WpmrWidget() {  
         //The constructor to the widget
}
function form($instance) {
        // The options form that will be shown on the admin widget
}
function update($new_instance, $old_instance) {
       // The options that will be saved when save button is clicked on admin widge options
}
function widget($args, $instance) {
       // The actual code that is executed to display the widget on the page.
}
}
?>

This is the beauty of wordpress. It hides all the internal operations and provides you flexibility to concentrate more on your business logic.

All wordpress widgets will have these four methods. The first is the constructor while the others are form, update and widget methods.

form:  The form method contains the options that are displayed on the widget panel.

update: The update method is executed before wordpress saves the options to the database. Here we an have some validation over the data submitted by the user.

widget: The widget method is the main method that is executed to display the widget on the page.

The parameter $instance in each of these methods contains the options saved for that widget instance.

The $args parameter in widget method contains the options passed by the theme developers to alter the display of the widget on their theme.

Write a Comment

Comment