Creating a WordPress widget – A simple text widget

Ernest Marcinko Blog, Tutorials, Wordpress 7 Comments

To understand the basics of widget creation, I recommend reading the following articles:

The basic widget structure is this (from the widget API):

class My_Widget extends WP_Widget {

	/**
	 * Sets up the widgets name etc
	 */
	public function __construct() {
		// widget actual processes
	}

	/**
	 * Outputs the content of the widget
	 *
	 * @param array $args
	 * @param array $instance
	 */
	public function widget( $args, $instance ) {
		// outputs the content of the widget
	}

	/**
	 * Ouputs the options form on admin
	 *
	 * @param array $instance The widget options
	 */
	public function form( $instance ) {
		// outputs the options form on admin
	}

	/**
	 * Processing widget options on save
	 *
	 * @param array $new_instance The new options
	 * @param array $old_instance The previous options
	 */
	public function update( $new_instance, $old_instance ) {
		// processes widget options to be saved
	}
}

There is little to no information about these functions, so the developer must figure out the ways of storing/viewing data inside this widget code.

Creating a simple text widget

The best way to understand the WordPress widget system is to try to create one. Here I will show you how to create a simple widget that shows a text that we save on the backend.

public function __construct()

This part of the widget class is meant to represent the initialisation of your widget. You can add widget title/description for the backend, or you can run some initial code as well.
A good example:

public function __construct() {
    $widget_ops = array('classname' => 'My_Widget', 'description' => 'Displays an My widget!' );
    $this->WP_Widget('My_Widget', 'My widget', $widget_ops);
}

You can copy and paste this code as most of the widgets doesn’t need more code in their constructors.

public function form( $instance )

The form function represents the admin options page of the widget, when dragged to any widgetized area. Before creating the actual output of the widget, we should take care of the basics on the backend. Some widgets require complicated locig on the backend before the output is created.
Let’s say we want to create a widget, that displays a text on the frontend:

public function form( $instance ) {

   // PART 1: Extract the data from the instance variable
   $instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
   $title = $instance['title'];
   $text = $instance['text'];   

   // PART 2-3: Display the fields
   ?>
   <!-- PART 2: Widget Title field START -->
   <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>
    <!-- Widget Title field END -->

   <!-- PART 3: Widget Text field START -->
   <p>
    <label for="<?php echo $this->get_field_id('text'); ?>">Text: 
      <input class="widefat" id="<?php echo $this->get_field_id('text'); ?>" 
             name="<?php echo $this->get_field_name('text'); ?>" type="text" 
             value="<?php echo attribute_escape($text); ?>" />
    </label>
    </p>
    <!-- Widget Text field END -->
   <?php

}

This function consists of 3 parts:

  • The extraction of the $instance variable with the default values
  • Part 2: Displaying the title field
  • Part 3: Displaying a simple text input field

This code is generally a good way to build up more complicated backend options. Once you understand the basics, it’s easy as 1 2 3.

function update($new_instance, $old_instance)

After displaying the title and the text field we need to make the widget able to save those values. The update function is called, whenever a widget is saved on the backend. It comes with two parameters: the reference of the new instande and the old instance.

A typical use of this function:

function update($new_instance, $old_instance) {
  $instance = $old_instance;
  $instance['title'] = $new_instance['title'];
  $instance['text'] = $new_instance['text'];
  return $instance;
}

That’s it. It gathers the new values of the new instance and mixes it with the old one. You can modify/filter/discard these values, or do whatever you need to do with them.

function widget($args, $instance)

Finally, after properly setting up the backend it’s time to generate the frontend code:

function widget($args, $instance) {
  // PART 1: Extracting the arguments + getting the values
  extract($args, EXTR_SKIP);
  $title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);
  $text = empty($instance['text']) ? '' : $instance['text'];

  // Before widget code, if any
  echo (isset($before_widget)?$before_widget:'');

  // PART 2: The title and the text output
  if (!empty($title))
    echo $before_title . $title . $after_title;;
  if (!empty($text))
    echo $text;

  // After widget code, if any  
  echo (isset($after_widget)?$after_widget:'');
}
  •  Part 1: Extracting the arguments and getting the saved $title and $text values
  • Part 2: Simply outputting the title and the content

This function code is also a good skeleton for a more advanced widget ouput. You can also use SHORTCODES in this output:

echo do_shortcode("some_shortcode[]");

 Initialize the widget

Finally, we need to initialize the widget. Usually this is done right after the widget class code, with the following line of code:

add_action( 'widgets_init', create_function('', 'return register_widget("My_Widget");') );

Get the code

PastebinDownload

Comments 7

  1. Pingback: WordPress – Widget select box | WordPress Dreams

  2. Dave

    Hello,

    I tried to download and install the plugin but it doesn’t work. It says:

    Installing Plugin from uploaded file: my_widget.zip
    Unpacking the package…

    Installing the plugin…

    The package could not be installed. No valid plugins were found.

    Plugin install failed.

    Thanks

    1. Ernest Marcinko Post
      Author
      Ernest Marcinko

      Hi Dave!

      It’s because this is not a plugin it’s only a sample widget file. It was meant as an example for plugin developers. If you include this file in your plugin it will work.

      Best regards,
      Ernest

  3. Jonathan Malm

    I used this code multiple times in an attempt to make multiple widgets. But in my sidebars, only the first widget shows up even though I’ve included multiple. Any idea why that might be?

  4. Bart

    After the latest update when visiting my widgets the text boxes (that I really need) are empty. I can’t change a thing, unless in the database. But then it doesn’t work anymore. Any suggestion ?

Leave a Reply

Your email address will not be published.