How to Create a Widget Plugin for WordPress – Part 2

How to Create a Widget Plugin for WordPress – Part 2

  • Published on: 12th November 2012
  • Author:
  • Under: Other
Post Series: How To Create A Widget Plugin For WordPress
  1. 1.How To Create A Widget Plugin For WordPress
  2. 2.How to Create a Widget Plugin for WordPress – Part 2

We saw last week the basics to create a WordPress widget plugin. Today I’ll be covering some new points to make a better plugin and to add extra features to the existing one. So if you have missed part one, i truly recommend you to have a look to part 1. You’ll need the code we saw last week to start this part 2.

Step 1 – Adding a checkbox field

First of all, we are going to add a checkbox field to our widget. Open the file you created in part one. In this step, we only have to add a new field, nothing really complex.

1 – The form() function

Lets’ start by the adding a new field type to the form() function:

// widget form creation
function form($instance) { 
// Check values if( $instance) { 
     $title = esc_attr($instance['title']); 
     $text = esc_attr($instance['text']); 
     $textarea = esc_textarea($instance['textarea']); 
     $checkbox = esc_attr($instance['checkbox']); // Added 
} else { 
     $title = ''; 
     $text = ''; 
     $textarea = ''; 
     $checkbox = ''; // Added 
} 
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Widget Title', 'wp_widget_plugin'); ?></label>
<input id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('text'); ?>"><?php _e('Text:', 'wp_widget_plugin'); ?></label>
<input id="<?php echo $this->get_field_id('text'); ?>" name="<?php echo $this->get_field_name('text'); ?>" type="text" value="<?php echo $text; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('textarea'); ?>"><?php _e('Textarea:', 'wp_widget_plugin'); ?></label>
<textarea id="<?php echo $this->get_field_id('textarea'); ?>" name="<?php echo $this->get_field_name('textarea'); ?>"><?php echo $textarea; ?></textarea>
</p>
<p>
<input id="<?php echo $this->get_field_id('checkbox'); ?>" name="<?php echo $this->get_field_name('checkbox'); ?>" type="checkbox" value="1" <?php checked( '1', $checkbox ); ?> />
<label for="<?php echo $this->get_field_id('checkbox'); ?>"><?php _e('Checkbox', 'wp_widget_plugin'); ?></label>
</p>
<?php }

The only difference here is that the input type is a checkbox, that means that we can use the WordPress built-in checked()¬†function. In two words this function is equivalent to a “if” statement that compares the variable value to another one.

2 – The update() function

In the update function, we only have to add a new variable corresponding to the checkbox field:

// update widget
function update($new_instance, $old_instance) {
      $instance = $old_instance;
      // Fields
      $instance['title'] = strip_tags($new_instance['title']);
      $instance['text'] = strip_tags($new_instance['text']);
      $instance['textarea'] = strip_tags($new_instance['textarea']);
      $instance['checkbox'] = strip_tags($new_instance['checkbox']);
     return $instance;
}

3 – The widget() function

In the widget() function we just have to check if $checkbox is set and if its value is equal to 1. You can then echo whatever you want.

// display widget
function widget($args, $instance) {
   extract( $args );
   // these are the widget options
   $title = apply_filters('widget_title', $instance['title']);
   $text = $instance['text'];
   $textarea = $instance['textarea'];
   echo $before_widget;
   // Display the widget
   echo '<div>';

   // Check if title is set
   if ( $title ) {
      echo $before_title . $title . $after_title;
   }

   // Check if text is set
   if( $text ) {
      echo '<p>'.$text.'</p>';
   }
   // Check if textarea is set
   if( $textarea ) {
     echo '<p>'.$textarea.'</p>';
   }
   // Check if checkbox is checked
   if( $checkbox AND $checkbox == '1' ) {
     echo '<p>'.__('Checkbox is checked', 'wp_widget_plugin').'</p>';
   }
   echo '</div>';
   echo $after_widget;
}

Please note that you could also use if( $checkbox == true ). In that case it doesn’t really matter, but if you want to change the value of $checkbox, the first method is better. And this is it! You just added a checkbox field to your widget!

Step 2 – Adding a select dropdown field

Let’s see now how to add a select dropdown field to our widget. The method is very similar to what we just did for the checkbox.

1 – The form() function

Lets’ start by the adding a new field type to the form() function:

// widget form creation
function form($instance) {

// Check values
if( $instance) {
     $title = esc_attr($instance['title']);
     $text = esc_attr($instance['text']);
     $textarea = esc_textarea($instance['textarea']);
     $checkbox = esc_attr($instance['checkbox']);
     $select = esc_attr($instance['select']); // Added
} else {
     $title = '';
     $text = '';
     $textarea = '';
     $checkbox = '';
     $select = ''; // Added
}
?>

<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Widget Title', 'wp_widget_plugin'); ?></label>
<input id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
</p>

<p>
<label for="<?php echo $this->get_field_id('text'); ?>"><?php _e('Text:', 'wp_widget_plugin'); ?></label>
<input id="<?php echo $this->get_field_id('text'); ?>" name="<?php echo $this->get_field_name('text'); ?>" type="text" value="<?php echo $text; ?>" />
</p>

<p>
<label for="<?php echo $this->get_field_id('textarea'); ?>"><?php _e('Textarea:', 'wp_widget_plugin'); ?></label>
<textarea id="<?php echo $this->get_field_id('textarea'); ?>" name="<?php echo $this->get_field_name('textarea'); ?>"><?php echo $textarea; ?></textarea>
</p>

<p>
<input id="<?php echo $this->get_field_id('checkbox'); ?>" name="<?php echo $this->get_field_name('checkbox'); ?>" type="checkbox" value="1" <?php checked( '1', $checkbox ); ?> />
<label for="<?php echo $this->get_field_id('checkbox'); ?>"><?php _e('Checkbox', 'wp_widget_plugin'); ?></label>
</p>

<p>
<label for="<?php echo $this->get_field_id('select'); ?>"><?php _e('Select', 'wp_widget_plugin'); ?></label>
<select name="<?php echo $this->get_field_name('select'); ?>" id="<?php echo $this->get_field_id('select'); ?>" class="widefat">
<?php
$options = array('lorem', 'ipsum', 'dolorem');
foreach ($options as $option) {
echo '<option value="' . $option . '" id="' . $option . '"', $select == $option ? ' selected="selected"' : '', '>', $option, '</option>';
}
?>
</select>
</p>
<?php
}

The new code is now adding a dropdown select with three options. You can customize options list by modifying the $options. You can add as many options as you want.

2 – The update() function

In the update() function, we have to what we did before: adding a new instance, nothing complicated here.

// update widget
function update($new_instance, $old_instance) {
      $instance = $old_instance;
      // Fields
      $instance['title'] = strip_tags($new_instance['title']);
      $instance['text'] = strip_tags($new_instance['text']);
      $instance['textarea'] = strip_tags($new_instance['textarea']);
      $instance['checkbox'] = strip_tags($new_instance['checkbox']);
      $instance['select'] = strip_tags($new_instance['select']);
     return $instance;
}

3 – The widget() function

It’s now time to display the select value on the website. As know already know, this part is done by the widget() function. What we are going to do now is to retrieve the select value and output it:

// display widget
function widget($args, $instance) {
   extract( $args );
   // these are the widget options
   $title = apply_filters('widget_title', $instance['title']);
   $text = $instance['text'];
   $textarea = $instance['textarea'];
   echo $before_widget;
   // Display the widget
   echo '<div>';

   // Check if title is set
   if ( $title ) {
      echo $before_title . $title . $after_title;
   }

   // Check if text is set
   if( $text ) {
      echo '<p>'.$text.'</p>';
   }

   // Check if textarea is set
   if( $textarea ) {
     echo '<p>'.$textarea.'</p>';
   }

   // Check if checkbox is checked
   if( $checkbox AND $checkbox == '1' ) {
     echo '<p>'.__('Check is checked', 'wp_widget_plugin').'</p>';
   }

   // Get $select value
	if ( $select == 'lorem' ) {
		echo 'Lorem option is Selected';
		} else if ( $select == 'ipsum' ) {
		echo 'ipsum option is Selected';
		} else {
		echo 'dolorem option is Selected';
	}

   echo '</div>';
   echo $after_widget;
}

Great! We have successfully added another field type to our widget! Well done! But what about radio buttons ? In fact in very similar to the new fields we’ve just added and I’m pretty sure with a bit of work you’ll manage to add it ;-)

Now that the widget is working and that we have our fields i would like to introduce you a few more techniques to customize the widget and make it your own.

Step 3 – Going a bit further

1 – Customizing the widget display

Well, all we did before was nice, but it’s time to go a bit further. There a few more things i’d like to show you to create really nice widgets. And the first one is about the constructor. Remember what we saw in part 1. The constructor was similar to this:

// constructor
    function wp_my_plugin() {
        parent::WP_Widget(false, $name = __('My Widget', 'wp_widget_plugin') );
    }

This is the basic way of declaring a plugin. But i would i like to add a description to the plugin (in the administration), modify its size and add a CSS class (still in the administration). To do so, we need to pass variables, here is how:

// Controller
function __construct() {
	$widget_ops = array('classname' => 'my_widget_class', 'description' => __('Insert the plugin description here', 'wp_widget_plugin'));
	$control_ops = array('width' => 400, 'height' => 300);
	parent::WP_Widget(false, $name = __('My Widget', 'wp_widget_plugin'), $widget_ops, $control_ops );
}

$widget_ops is adding a CSS class and the description to the widget box while $control_ops is modifying the plugin height and width.

2 – Adding auto-paragraph to textareas

The second point i’d like to see is the auto-paragraph creation with textareas. If you test now your plugin you’ll see that if you insert text containing paragraphs (and HTML), after you saved the content, the text becomes a plain text, and you lost your paragraphs. Here is how to deal with that point. To allow auto-paragraphs creation for the textarea field modify this line in widget() function:

$textarea = $instance['textarea'];

Replace it by this one:

$textarea = apply_filters( 'widget_textarea', empty( $instance['textarea'] ) ? '' : $instance['textarea'], $instance );

and then in the function, replace:

// Check if textarea is set
   if( $textarea ) {
     echo '<p>'.$textarea.'</p>'; }

by this:

if( $textarea ) { echo wpautop($textarea); }

and finally in update() function, replace:

$instance['textarea'] = strip_tags($new_instance['textarea']);

by this:

if ( current_user_can('unfiltered_html') )
		$instance['textarea'] =  $new_instance['textarea'];
	else
		$instance['textarea'] = stripslashes( wp_filter_post_kses( addslashes($new_instance['textarea']) ) );

This part is a bit tricky, but when it’s done, you’ll get the entire satisfaction to have a really nice widget!

Conclusion

We saw that creating a widget inside a plugin is very interesting, now you must know how to create a simple plugin containing a widget with different field types and you learnt how to go a bit further using advanced techniques to customize the widget. Congratulations, you did an amazing job!

Remi
Remi is an expert WordPress developer that coded many great free and premium themes and plugins. His experience on WordPress allows him to produce great stuff and to propose advanced tutorials. (remicorson.com)
Remi
This article has 13 comments
  1. Liam Dang says:

    Great Tutorial!

    1. Remi says:

      Thanks Liam !

      Author
    2. AJ Clarke | WPExplorer says:

      @Liam – Remi is awesome – expect to see many more great tutorials like this in the future ;)

      Admin
      1. Remi says:

        Wow! Thanks you AJ, but you already proved to us that you are much more talented than me!

        Author
  2. Bucur says:

    very nice job Remi…

    1. Remi says:

      Thanks!

  3. Jelle says:

    Well done Remi, looks great! However, it could be useful for some people of you’d add a: ‘download files’ link in your article, so people can download the final code. Nevertheless: you did an amazing job, thank you for that!

    1. Remi says:

      Thanks!

      Author
  4. Peter Arnell says:

    Great tutorial, thanks. Helped alot.

  5. Daniel says:

    Hey Remi,
    First of all I want to say a bit thanks for posting this article, it really helped me a lot.
    But I have a question: Shouldn’t there be a “$select = $instance['select'];” between the 7th and the 9th line of this piece of code http://awesomescreenshot.com/0501mg6fe8 ?

    Again, thanks for sharing this tutorial! :)

  6. ritshidze says:

    thank you very much… you the man…

  7. Agent Bey says:

    This oneof the best tutorial I have use for php. Your team rocks! I wanted to take the drop down field to another level. I would like the drop down field to show a list of pages. User would then select a page. Page URL is used to create a button in the widget form.

    Any direction you can provide is much appreciated. Thank you!

Sorry, comments are now closed.