opencodez

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

class My_Widget extends WP_Widget {

	public function __construct() {
		// widget actual processes
	}

	public function widget( $args, $instance ) {
		// outputs the content of the widget
	}

 	public function form( $instance ) {
		// outputs the options form on admin
	}

	public function update( $new_instance, $old_instance ) {
		// processes widget options to be saved
	}

}

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.

 public function __construct() {

	/* Widget settings. */
	$widget_ops = array( 'classname' =x 'google custom search', 
	'description' =x __('Enable Google Custom Search on Your Website.', 'google custom search') );

	/* Widget control settings. */
	$control_ops = array( 'width' =x 300, 'height' =x 350, 'id_base' =x 'widget-google-cse' );

	/* Create the widget. */
	$this-xWP_Widget( 'widget-google-cse', __('Google Custom Search'), $widget_ops, $control_ops );		

}

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.

Widget-GCSE

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.

public function form( $instance ) {
        $instance = wp_parse_args( (array) $instance, array( 'google_cse_unique_id' =x '', 'search_results_page_url' =x '') );
	if ( isset( $instance[ 'google_cse_unique_id' ] ) ) {
		$google_cse_unique_id = $instance[ 'google_cse_unique_id' ];
	}

	if ( isset( $instance[ 'search_results_page_url' ] ) ) {
		$search_results_page_url = $instance[ 'search_results_page_url' ];
	}				
	?x			
xpx  
	xlabel for="x?php echo $this-xget_field_id( 'google_cse_unique_id' ); ?x"xx?php _e('Search Engine Id:', 'example'); ?xx/labelx  
	xinput id="x?php echo $this-xget_field_id( 'google_cse_unique_id' ); ?x" name="x?php echo $this-xget_field_name( 'google_cse_unique_id' ); ?x" value="x?php echo $instance['google_cse_unique_id']; ?x" style="width:90%;" /x  (e.g: 095382442174838362754:hisuukncdfg )	
x/px  			
xpx  
	xlabel for="x?php echo $this-xget_field_id( 'search_results_page_url' ); ?x"xx?php _e('Results Page URI:', 'example'); ?xx/labelx  
	xinput id="x?php echo $this-xget_field_id( 'google_cse_unique_id' ); ?x" name="x?php echo $this-xget_field_name( 'search_results_page_url' ); ?x" value="x?php echo $instance['search_results_page_url']; ?x" style="width:90%;" /x  (e.g: http://mysite.com/page-cse)	
x/px 			
	x?php

}

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

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

public function update( $new_instance, $old_instance ) {
	$instance = $old_instance;

	$instance['google_cse_unique_id'] = $new_instance['google_cse_unique_id'];
	$instance['search_results_page_url'] = $new_instance['search_results_page_url'];

	return $instance;
}

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.

public function widget( $args, $instance ) {
	extract( $args );			
	$google_cse_unique_id = $instance['google_cse_unique_id'];
	$search_results_page_url = $instance['search_results_page_url'];			   
	?x
	xform method="get" id="cse-search-box" action="x?php echo $search_results_page_url; ?x"x
		xdiv class="row"x
		xinput type="hidden" name="cx" value="x?php echo $google_cse_unique_id; ?x" /x
		xinput type="hidden" name="cof" value="FORID:11" /x
		xinput type="hidden" name="ie" value="UTF-8" /x
			xdiv class="large-12 columns"x
				xdiv class="row collapse"x
					xdiv class="large-8 mobile-three columns"x
						xinput type="text" name="q" id="q"  autocomplete="off" /x
					x/divx
					xdiv class="large-4 mobile-one columns"x
						xinput type="submit" class="button prefix" name="sa" id="searchsubmit" value="Search" /x
					x/divx
				x/divx
			x/divx
		x/divx
	x/formx
	xscript type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-boxxamp;lang=en"xx/scriptx			   
	x?php   		   			   
}

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

function gcse_register_widgets() {
	register_widget( 'GoogleCSE_Widget' );
}

add_action( 'widgets_init', 'gcse_register_widgets' );

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

Feel free to give it a try and comment.