How to add a Widget to WordPress

Many WordPress Themes come Widget Ready that boosts functionality of a site considerably. These widget ready platform saves a lot of time of webmaster to search for plugins and install it. Today in this article we will see how a theme developer can add a Widget to WordPress easily. We will be looking the widget that will help us to add Google Custom Search to our web site. You can change look and feel as per your theme.

Lets get in to coding part now. When we develop our widget we need to extend WP_Widget class from WordPress and implement four basic functions to get our widget working. Here is the default usage

Function Reference:

__Construct: It is the constructor of our class. Here we will do all the initialization of parameters. We will define widget id, class, its admin panels height etc.

Form: This method outputs the admin form you have for your widget. You need to plan and write your html carefully here.

Update: This function is used to save the options that are used in widget. Before you add this option you need to use add_option function and add the parameters you intend to use to database.

Widget: Main function that send output to your website. You can writer PHP/HTML code here that suits your websites theme.

Ok, now lets turn to our Google Custom Search Widget. Here is my constructor where I am going to specify the title and other stuff.

and you can see this in action on widget panel of wordpress as shown here. You can see how options set in the constructor are getting used.



Next is our admin form for this widget. Google CSE needs publisher id and destination results page url to work properly. I am providing these parameters as options in this form. These parameters can be saved and updated.

the variables passed while function call are automatically populated by wordpress framework, you dont need to worry about them. Here is the output
Widget - Google Custom Search Engine

Now a simple method update, where we are saving all the parameters from our admin form to database.

If you see I am simply overwriting old values with new and returning the updated value array. The rest is handled by default.

Next is our function which is responsible for your widget to show some magic on your site. You need to carefully plan its code as per your sites theme and design. Basically I decided to go for custom widget for CSE because none of the available plugin were providing code that fits in to my theme.

Lastly and most importantly DO NOT FORGET to register your class with WordPress framework as –

Simple isn’t it. Just put all above functions in a class file. Add that class to your framework and you are ready to go. Here is simple yet elegant Google Custom Search widget that I am using on my site.Google CSE

Feel free to give it a try and comment.

Add a Comment

Your email address will not be published. Required fields are marked *