Advertisement
Creative Coding

Building Custom WordPress Widgets

by

Building WordPress widgets is just like building a plugin but it is more simple and straightforward. All you need to do is have a single file in which all the PHP goes and it's easier to code than a plugin which can have more than one file. There are three major functions of a widget which can be broken down into widget, update and form.

  • function widget()
  • function update()
  • function form()

Basic Structure

The basic outline of our widget is very simple and there are a handful of functions that you'll need to know. The bare bone structure of our widget is something like this:

add_action( 'widgets_init', 'register_my_widget' );	// function to load my widget

function register_my_widget() {}						// function to register my widget

class My_Widget extends WP_Widget () {}		// The example widget class

function My_Widget() {}						// Widget Settings

function widget() {}						// display the widget

function update() {}						// update the widget

function form() {}							// and of course the form for the widget options

Step 1

Before we do all that we'll first load our widget whenever necessary by the function "widget_init". This is an action hook and you can find more about it in the WordPress codex.

add_action( 'widgets_init', 'register_my_widget' );

Next thing that we'll do is register our widget in WordPress so that it is available under the widgets section.

function register_my_widget() {
	register_widget( 'My_Widget' );
}

Step 2

We will enclose our widget in a class. The name of the class is important! One thing that should be kept in mind is that the name of the class and the name of the function should be the same.

class My_Widget extends WP_Widget {}

Now we'll pass some setting parameters to this class. For example we can pass this the width and height. We can also give our widget a little description if we want to, which is useful if you are bundling this widget with your commercial theme.

function My_Widget() {
	function My_Widget() {
		$widget_ops = array( 'classname' => 'example', 'description' => __('A widget that displays the authors name ', 'example') );
		$control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'example-widget' );
		$this->WP_Widget( 'example-widget', __('Example Widget', 'example'), $widget_ops, $control_ops );
	}

Now that we have completed the basic requirements for our widget, we'll move our attention to the three functions that we talked about earlier which are the important functions or the main building blocks of our widget!


Step 3 Function Widget()

The first function is related with the display of our widget. We'll pass a couple of arguments to our widget function. We'll be passing arguments from the theme, which can be a title and other specific values. Next we are passing the instance variable, which is related with the class of our function.

function widget( $args, $instance )

After that we'll extract the values from the argument because we want the values to be available locally. If you don't know what this local variable is all about, just don't worry about it right now and simply add this step!

extract( $args );

Next up we will be setting the title and other values for our widget, which can be edited by the user under the widgets menu. We are also including the special variables like $before_widget, $after_widget. These values are handled by the theme.

$title = apply_filters('widget_title', $instance['title'] );
$name = $instance['name'];
$show_info = isset( $instance['show_info'] ) ? $instance['show_info'] : false;

echo $before_widget;

// Display the widget title 
if ( $title )
	echo $before_title . $title . $after_title;

//Display the name 
if ( $name )
	printf( '<p>' . __('Hey their Sailor! My name is %1$s.', 'example') . '</p>', $name );

if ( $show_info )
	printf( $name );

echo $after_widget;

Step 4 Update Function()

Next up is the update function. This function will take the user settings and save them. It will just update the settings according to the user's taste.

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

	//Strip tags from title and name to remove HTML
	$instance['title'] = strip_tags( $new_instance['title'] );
	$instance['name'] = strip_tags( $new_instance['name'] );
	$instance['show_info'] = $new_instance['show_info'];

	return $instance;
}

One thing to note here is that we are stripping the values so that any XHTML can be removed from the text which, in simple words, might affect the working of our widget.


Step 5 Form Function()

The next step will outline creating the form which will serve as the input box. This will take in the user defined settings and values. The form function can include checkboxes, text input boxes etc.

Before we create these input fields, we'll have to decide what to show when the user doesn't select anything from the widget. To do this we will pass some default values to it like title, description etc.

//Set up some default widget settings.
$defaults = array( 'title' => __('Example', 'example'), 'name' => __('Bilal Shaheen', 'example'), 'show_info' => true );
$instance = wp_parse_args( (array) $instance, $defaults ); ?>

Now we'll create the input text box. We will enclose these options within the paragraph enclosing tag.

// Widget Title: Text Input
<p>
	<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'example'); ?></label>
	<input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" style="width:100%;" />
</p>

//Text Input 
<p>
	<label for="<?php echo $this->get_field_id( 'name' ); ?>"><?php _e('Your Name:', 'example'); ?></label>
	<input id="<?php echo $this->get_field_id( 'name' ); ?>" name="<?php echo $this->get_field_name( 'name' ); ?>" value="<?php echo $instance['name']; ?>" style="width:100%;" />
</p>


// Checkbox
<p>
	<input class="checkbox" type="checkbox" <?php checked( $instance['show_info'], true ); ?> id="<?php echo $this->get_field_id( 'show_info' ); ?>" name="<?php echo $this->get_field_name( 'show_info' ); ?>" /> 
	<label for="<?php echo $this->get_field_id( 'show_info' ); ?>"><?php _e('Display info publicly?', 'example'); ?></label>
</p>

Conclusion

And that's it. You just made yourself a very nice and simple widget which displays the name of the author of the blog. Furthermore it gives the option to the user whether or not to show it publicly to the audience. Save the code in a PHP file and upload it to your theme directory. Call it in your functions.php. After that go to your widgets panel and you will see the newly created widget.

All the code is included in the download file so that makes it easier to copy and paste. Have fun!

Related Posts
  • Code
    Creative Coding
    Using the Included Password Strength Meter Script in WordPressPassword meter 400
    WordPress uses a pretty nifty password strength script that is used to display whether the passwords you entered in the WordPress admin are: not the same, very weak, weak, medium or strong. Currently this script is only used when creating creating new users and when changing your password in your admin. In this article, I will be teaching you on how to use the WordPress' password strength meter in your own forms.Read More…
  • Code
    Theme Development
    Custom Controls in the Theme CustomizerTheme customizer custom control 400
    In the last article, we explored the advanced controls available in the Theme Customizer, and how to implement them. We’re going to look at how to create our own custom control, allowing you to choose which Category of Posts are displayed on the home page. To get started, download version 0.6.0 of our Theme Customizer Example.Read More…
  • Code
    PHP
    Acceptance Testing With CodeceptionIntro to codeception retina preview
    Typically new features for web applications are tested by visiting the appropriate page in a browser, maybe filling out some form data, submitting the form, and then developers or testers hope to see their desired result. This is the natural way most web developers test their apps. We can continue with this natural testing process and improve upon it to ensure our apps are as stable as possible by using Codeception. Read More…
  • Code
    Plugins
    A Better Forum List Widget for bbPressBbpress
    When bbPress was still a standalone installation, I had tried it out and wasn't really impressed. Things were clunky and it didn't always work the way it was supposed to. After languishing for a few years, Automattic decided to take bbpress and turn it into a plugin, improving the functionality leaps and bounds and making it a strong contender amongst other forum option for WordPress.Read More…
  • Code
    Widgets
    Building a Countdown Timer WidgetBuilding a countdown timer widget preview
    We all love a celebration, and now that Easter is over, we look forward to the next occasion. How far away is the next occasion you like to celebrate? Whatever it might be, let's build a widget plugin to add a countdown timer to our sidebar showing how long we have left to wait.Read More…
  • Code
    Widgets
    Twitter Trends Widget for WordPressPreview
    In this tutorial we are going to create a WordPress widget that displays Twitter Trends by region. We will use Twitter's Trends API and update trends after a specific time duration using WordPress' Transients API.Read More…