<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Jesse Altman &#187; Tutorial</title>
	<atom:link href="http://jessealtman.com/category/tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>http://jessealtman.com</link>
	<description>This is the personal blog and hub for all things about Jesse Altman, a 21 year old web developer and business manager. Feel free to browse around...</description>
	<lastBuildDate>Mon, 26 Oct 2009 15:49:58 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Tutorial: WordPress 2.8 Widget API</title>
		<link>http://jessealtman.com/2009/06/08/tutorial-wordpress-28-widget-api/</link>
		<comments>http://jessealtman.com/2009/06/08/tutorial-wordpress-28-widget-api/#comments</comments>
		<pubDate>Tue, 09 Jun 2009 03:54:16 +0000</pubDate>
		<dc:creator>Jesse Altman</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://jessealtman.com/?p=212</guid>
		<description><![CDATA[One of the many nice new features of WordPress 2.8 is the inclusion of a new widget API. As most of you probably know, my company Spiral Web Consulting maintains Google Analyticator which recently added a Google Analytics stat widget. When I heard WordPress was introducing a new widget API, I decided it would be [...]]]></description>
			<content:encoded><![CDATA[<p>One of the many nice new features of WordPress 2.8 is the inclusion of a new widget API. As most of you probably know, my company <a href="http://spiralwebconsulting.com/">Spiral Web Consulting</a> maintains <a href="http://plugins.spiralwebconsulting.com/">Google Analyticator</a> which recently added a Google Analytics stat widget. When I heard WordPress was introducing a new widget API, I decided it would be fun to add API support to the existing Google Analytics stat widget. When looking through the <a href="http://codex.wordpress.org/Widgets_API">Codex&#8217;s explanation of the new API</a>, I realized they did not really include a good tutorial on how to create a widget using the API.</p>
<p>In this tutorial, I will teach you how to create a Hello World sidebar widget using the WordPress 2.8 widget API. I will provide the code throughout this post, and also provide the examples for download at the end of the post. This example will be demonstrated on the Default WordPress theme and provide two configurable lines of text that can be modified.</p>
<p><span id="more-212"></span>There are three main functions that every widget must include. These functions include <code>widget(), update(),</code> and <code>form()</code> and are each responsible for a different part of the widget. Let&#8217;s take a brief look at each function.</p>
<h2>widget()</h2>
<pre>
/**
  * Displays the Widget
  *
  */
  function widget($args, $instance){
    extract($args);
    $title = apply_filters(&#39;widget_title&#39;, empty($instance[&#39;title&#39;]) ? &#39;&amp;nbsp;&#39; : $instance[&#39;title&#39;]);
    $lineOne = empty($instance[&#39;lineOne&#39;]) ? &#39;Hello&#39; : $instance[&#39;lineOne&#39;];
    $lineTwo = empty($instance[&#39;lineTwo&#39;]) ? &#39;World&#39; : $instance[&#39;lineTwo&#39;];

    # Before the widget
    echo $before_widget;

    # The title
    if ( $title )
    echo $before_title . $title . $after_title;

    # Make the Hello World Example widget
    echo &#39;&lt;div style=&quot;text-align:center;padding:10px;&quot;&gt;&#39; . $lineOne . &#39;&lt;br /&gt;&#39; . $lineTwo . &quot;&lt;/div&gt;&quot;;

    # After the widget
    echo $after_widget;
}</pre>
<p><br/></p>
<p>The <code>widget()</code> function will be the first function we delve into. This function is responsible for displaying the widget. The above function was created for the Hello World example. This function will always require two parameters, <code>$args</code> and <code>$instance</code>.</p>
<p><code>$args</code> contains the native WordPress variables for the widget that some themes use to ensure the widget is used properly. <code>extract($args);</code> creates those variables, such as <code>$before_widget, $before_title, $after_title,</code> and <code>$after_widget</code>. These are important to include to ensure that all themes will be compatible with your widget.</p>
<p><code>$instance</code> is the instance of your widget that is currently being passed to the function. WordPress 2.8&#8217;s widget API adds the ability to have multiple instances of each widget. <code>$instance</code> is an array that will store all of your widget&#8217;s configurable options, which in this case is <code>$title, $lineOne,</code> and <code>$lineTwo</code>. It is important to note that when calling for each option, you should use an if statement to ensure that if the string was empty that the default will be used. This may not be necessary for each element so use desecration when doing this, but it can be useful when you do not want a certain value to be left empty. Another important thing to note is that there are certain WordPress values that WordPress will use differently. For instance, <code>$title</code> has a special filter applied because it is the title of the widget which WordPress recognizes.</p>
<h2>update()</h2>
<pre>
/**
  * Saves the widgets settings.
  *
  */
  function update($new_instance, $old_instance){
    $instance = $old_instance;
    $instance[&#39;title&#39;] = strip_tags(stripslashes($new_instance[&#39;title&#39;]));
    $instance[&#39;lineOne&#39;] = strip_tags(stripslashes($new_instance[&#39;lineOne&#39;]));
    $instance[&#39;lineTwo&#39;] = strip_tags(stripslashes($new_instance[&#39;lineTwo&#39;]));

  return $instance;
}</pre>
<p></p>
<p><code>update()</code> is by far the simplest of the three functions. All <code>update()</code> does is save the values of each of the configurable options for the widget. </p>
<p>The <code>update()</code> function takes two different parameters, <code>$new_instance</code> and <code>$old_instance</code>. These variables are rather self explanatory. The old instance(<code>$old_instance</code>) is overwritten by the new instance(<code>$new_instance</code>) which values are taken from the widget form.</p>
<p>Always be sure to include the proper PHP functions such as <code>strip_tags()</code> and <code>stripslashes()</code> to ensure that no matter what a user puts in the widget options, they will not break the page the widget appears on.</p>
<h2>form()</h2>
<pre>
/**
  * Creates the edit form for the widget.
  *
  */
  function form($instance){
    //Defaults
    $instance = wp_parse_args( (array) $instance, array(&#39;title&#39;=&gt;&#39;&#39;, &#39;lineOne&#39;=&gt;&#39;Hello&#39;, &#39;lineTwo&#39;=&gt;&#39;World&#39;) );

    $title = htmlspecialchars($instance[&#39;title&#39;]);
    $lineOne = htmlspecialchars($instance[&#39;lineOne&#39;]);
    $lineTwo = htmlspecialchars($instance[&#39;lineTwo&#39;]);

    # Output the options
    echo &#39;&lt;p style=&quot;text-align:right;&quot;&gt;&lt;label for=&quot;&#39; . $this-&gt;get_field_name(&#39;title&#39;) . &#39;&quot;&gt;&#39; . __(&#39;Title:&#39;) . &#39; &lt;input style=&quot;width: 250px;&quot; id=&quot;&#39; . $this-&gt;get_field_id(&#39;title&#39;) . &#39;&quot; name=&quot;&#39; . $this-&gt;get_field_name(&#39;title&#39;) . &#39;&quot; type=&quot;text&quot; value=&quot;&#39; . $title . &#39;&quot; /&gt;&lt;/label&gt;&lt;/p&gt;&#39;;
    # Text line 1
    echo &#39;&lt;p style=&quot;text-align:right;&quot;&gt;&lt;label for=&quot;&#39; . $this-&gt;get_field_name(&#39;lineOne&#39;) . &#39;&quot;&gt;&#39; . __(&#39;Line 1 text:&#39;) . &#39; &lt;input style=&quot;width: 200px;&quot; id=&quot;&#39; . $this-&gt;get_field_id(&#39;lineOne&#39;) . &#39;&quot; name=&quot;&#39; . $this-&gt;get_field_name(&#39;lineOne&#39;) . &#39;&quot; type=&quot;text&quot; value=&quot;&#39; . $lineOne . &#39;&quot; /&gt;&lt;/label&gt;&lt;/p&gt;&#39;;
    # Text line 2
    echo &#39;&lt;p style=&quot;text-align:right;&quot;&gt;&lt;label for=&quot;&#39; . $this-&gt;get_field_name(&#39;lineTwo&#39;) . &#39;&quot;&gt;&#39; . __(&#39;Line 2 text:&#39;) . &#39; &lt;input style=&quot;width: 200px;&quot; id=&quot;&#39; . $this-&gt;get_field_id(&#39;lineTwo&#39;) . &#39;&quot; name=&quot;&#39; . $this-&gt;get_field_name(&#39;lineTwo&#39;) . &#39;&quot; type=&quot;text&quot; value=&quot;&#39; . $lineTwo . &#39;&quot; /&gt;&lt;/label&gt;&lt;/p&gt;&#39;;
}</pre>
<p></p>
<p>The final piece of the trifecta, <code>form()</code>, is used to display the form that is used on the WordPress admin interface when creating the widget. This form should include the proper input options for each configurable setting for the widget. It is important to note, WordPress now provides both the Save and Remove buttons natively, and it is not necessary to code in those buttons.</p>
<p>This function should also include an array of default values which will be used to populate the form the first time the widget is called in the WordPress admin interface.</p>
<p>WordPress 2.8 now has two different functions that are used in conjunction with the form. <code>get_field_name()</code> and <code>get_field_id()</code> will provide you will the correct field names and ids for each configurable option. This code is necessary in order to enable multiple instances of your widget.</p>
<p>If you are developing a plugin to be used in multiple languages, you must provide localization support by encapsulating your text with <code>__( )</code>. I don&#8217;t want to get into localization, so if you are planning on working with multiple languages you will need to look that up.</p>
<h2>Piecing It All Together</h2>
<p>So you have the three new functions and you are ready to make your widget a reality. Let&#8217;s take a look at the beginning of the Hello World example widget.</p>
<pre>
&lt;?php
/*
 * Plugin Name: Hello World Example
 * Version: 1.0
 * Plugin URI: http://jessealtman.com/2009/06/08/tutorial-wordpress-28-widget-api/
 * Description: Hello World example widget using the the WordPress 2.8 widget API. This is meant strictly as a means of showing the new API using the &lt;a href=&quot;http://jessealtman.com/2009/06/08/tutorial-wordpress-28-widget-api/&quot;&gt;tutorial&lt;/a&gt;.
 * Author: Jesse Altman
 * Author URI: http://jessealtman.com/
 */
class HelloWorldWidget extends WP_Widget
{
 /**
  * Declares the HelloWorldWidget class.
  *
  */
    function HelloWorldWidget(){
    $widget_ops = array(&#39;classname&#39; =&gt; &#39;widget_hello_world&#39;, &#39;description&#39; =&gt; __( &quot;Example widget demoing WordPress 2.8 widget API&quot;) );
    $control_ops = array(&#39;width&#39; =&gt; 300, &#39;height&#39; =&gt; 300);
    $this-&gt;WP_Widget(&#39;helloworld&#39;, __(&#39;Hello World Example&#39;), $widget_ops, $control_ops);
    }
</pre>
<p></p>
<p>In order to get WordPress to recognize this plugin, you need to give it the proper header. You should include a Plugin Name, Version, Plugin URI, Description, Author, and Author URI.</p>
<p>The next thing you need to do is declare your class. The class should be named something similar to what your widget is called. This class must extend the WP_Widget class in order to function properly. As with any class, you must give it a declaration. </p>
<p>In the class declaration, you need to have a few variables.<code>$widget_ops</code> contains the class name and the description of the widget. WordPress&#8217; admin interface will use this to display the correct information for your widget. I opted to use <code>$control_ops</code> which is an optional parameter that can be passed to the WP_Widget function that will specify the width and height of the WordPress admin interface options menu for your widget. The final function in the class description is WP_Widget and must always be in the class declaration. This function creates your widget in the WordPress admin interface.</p>
<p>Following the class declaration you should provide the <code>widget(), update(),</code> and <code>form()</code> functions to your file. You can then create custom functions used throughout the class. You should place these functions after the <code>form()</code> function.</p>
<h2>Wrapping It Up</h2>
<p>In order to finish the widget, you need to register it. Let&#8217;s take a look at the end of the Hello World example widget.</p>
<pre>
}// END class

/**
  * Register Hello World widget.
  *
  * Calls &#39;widgets_init&#39; action after the Hello World widget has been registered.
  */
  function HelloWorldInit() {
  register_widget(&#39;HelloWorldWidget&#39;);
  }
  add_action(&#39;widgets_init&#39;, &#39;HelloWorldInit&#39;);
?&gt;
</pre>
<p></p>
<p>First thing to notice is that this is outside of the HelloWorldWidget class. You must not include the final function in your class. The <code>HelloWorldInit()</code> function uses the <code>register_widget()</code> function provided by WordPress. This function will register the widget with WordPress and allow users to access it via the WordPress admin interface. The <code>add_action()</code> function is also WordPress specific. This function will add your <code>HelloWorldInit()</code> function to WordPress&#8217; <code>widget_init()</code> function. This ensures your widget is run when WordPress initiates widgets.</p>
<h2>Finished Product</h2>
<pre>
&lt;?php
/*
 * Plugin Name: Hello World Example
 * Version: 1.0
 * Plugin URI: http://jessealtman.com/2009/06/08/tutorial-wordpress-28-widget-api/
 * Description: Hello World example widget using the the WordPress 2.8 widget API. This is meant strictly as a means of showing the new API using the &lt;a href=&quot;http://jessealtman.com/2009/06/08/tutorial-wordpress-28-widget-api/&quot;&gt;tutorial&lt;/a&gt;.
 * Author: Jesse Altman
 * Author URI: http://jessealtman.com/
 */
class HelloWorldWidget extends WP_Widget
{
 /**
  * Declares the HelloWorldWidget class.
  *
  */
    function HelloWorldWidget(){
    $widget_ops = array(&#39;classname&#39; =&gt; &#39;widget_hello_world&#39;, &#39;description&#39; =&gt; __( &quot;Example widget demoing WordPress 2.8 widget API&quot;) );
    $control_ops = array(&#39;width&#39; =&gt; 300, &#39;height&#39; =&gt; 300);
    $this-&gt;WP_Widget(&#39;helloworld&#39;, __(&#39;Hello World Example&#39;), $widget_ops, $control_ops);
    }

  /**
    * Displays the Widget
    *
    */
    function widget($args, $instance){
      extract($args);
      $title = apply_filters(&#39;widget_title&#39;, empty($instance[&#39;title&#39;]) ? &#39;&amp;nbsp;&#39; : $instance[&#39;title&#39;]);
      $lineOne = empty($instance[&#39;lineOne&#39;]) ? &#39;Hello&#39; : $instance[&#39;lineOne&#39;];
      $lineTwo = empty($instance[&#39;lineTwo&#39;]) ? &#39;World&#39; : $instance[&#39;lineTwo&#39;];

      # Before the widget
      echo $before_widget;

      # The title
      if ( $title )
      echo $before_title . $title . $after_title;

      # Make the Hello World Example widget
      echo &#39;&lt;div style=&quot;text-align:center;padding:10px;&quot;&gt;&#39; . $lineOne . &#39;&lt;br /&gt;&#39; . $lineTwo . &quot;&lt;/div&gt;&quot;;

      # After the widget
      echo $after_widget;
  }

  /**
    * Saves the widgets settings.
    *
    */
    function update($new_instance, $old_instance){
      $instance = $old_instance;
      $instance[&#39;title&#39;] = strip_tags(stripslashes($new_instance[&#39;title&#39;]));
      $instance[&#39;lineOne&#39;] = strip_tags(stripslashes($new_instance[&#39;lineOne&#39;]));
      $instance[&#39;lineTwo&#39;] = strip_tags(stripslashes($new_instance[&#39;lineTwo&#39;]));

    return $instance;
  }

  /**
    * Creates the edit form for the widget.
    *
    */
    function form($instance){
      //Defaults
      $instance = wp_parse_args( (array) $instance, array(&#39;title&#39;=&gt;&#39;&#39;, &#39;lineOne&#39;=&gt;&#39;Hello&#39;, &#39;lineTwo&#39;=&gt;&#39;World&#39;) );

      $title = htmlspecialchars($instance[&#39;title&#39;]);
      $lineOne = htmlspecialchars($instance[&#39;lineOne&#39;]);
      $lineTwo = htmlspecialchars($instance[&#39;lineTwo&#39;]);

      # Output the options
      echo &#39;&lt;p style=&quot;text-align:right;&quot;&gt;&lt;label for=&quot;&#39; . $this-&gt;get_field_name(&#39;title&#39;) . &#39;&quot;&gt;&#39; . __(&#39;Title:&#39;) . &#39; &lt;input style=&quot;width: 250px;&quot; id=&quot;&#39; . $this-&gt;get_field_id(&#39;title&#39;) . &#39;&quot; name=&quot;&#39; . $this-&gt;get_field_name(&#39;title&#39;) . &#39;&quot; type=&quot;text&quot; value=&quot;&#39; . $title . &#39;&quot; /&gt;&lt;/label&gt;&lt;/p&gt;&#39;;
      # Text line 1
      echo &#39;&lt;p style=&quot;text-align:right;&quot;&gt;&lt;label for=&quot;&#39; . $this-&gt;get_field_name(&#39;lineOne&#39;) . &#39;&quot;&gt;&#39; . __(&#39;Line 1 text:&#39;) . &#39; &lt;input style=&quot;width: 200px;&quot; id=&quot;&#39; . $this-&gt;get_field_id(&#39;lineOne&#39;) . &#39;&quot; name=&quot;&#39; . $this-&gt;get_field_name(&#39;lineOne&#39;) . &#39;&quot; type=&quot;text&quot; value=&quot;&#39; . $lineOne . &#39;&quot; /&gt;&lt;/label&gt;&lt;/p&gt;&#39;;
      # Text line 2
      echo &#39;&lt;p style=&quot;text-align:right;&quot;&gt;&lt;label for=&quot;&#39; . $this-&gt;get_field_name(&#39;lineTwo&#39;) . &#39;&quot;&gt;&#39; . __(&#39;Line 2 text:&#39;) . &#39; &lt;input style=&quot;width: 200px;&quot; id=&quot;&#39; . $this-&gt;get_field_id(&#39;lineTwo&#39;) . &#39;&quot; name=&quot;&#39; . $this-&gt;get_field_name(&#39;lineTwo&#39;) . &#39;&quot; type=&quot;text&quot; value=&quot;&#39; . $lineTwo . &#39;&quot; /&gt;&lt;/label&gt;&lt;/p&gt;&#39;;
  }

}// END class

/**
  * Register Hello World widget.
  *
  * Calls &#39;widgets_init&#39; action after the Hello World widget has been registered.
  */
  function HelloWorldInit() {
  register_widget(&#39;HelloWorldWidget&#39;);
  }
  add_action(&#39;widgets_init&#39;, &#39;HelloWorldInit&#39;);
?&gt;
</pre>
<p></p>
<p>If you combine all of these code snippets together, this is what your final PHP file should look like. Click the images for a larger view.</p>
<p>Single Widget &#8211; Front End<br />
<a href="http://jessealtman.com/wp-content/uploads/2009/06/widget-frontend-single.png" target="_blank"><img src="http://jessealtman.com/wp-content/uploads/2009/06/widget-frontend-single-thumb.png" alt="Single Widget Front End"></a><br />
<br />
Single Widget &#8211; Back End<br />
<a href="http://jessealtman.com/wp-content/uploads/2009/06/widget-backend-single.png" target="_blank"><img src="http://jessealtman.com/wp-content/uploads/2009/06/widget-backend-single-thumb.png" alt="Single Widget Back End"></a><br />
<br />
Double Widget &#8211; Front End<br />
<a href="http://jessealtman.com/wp-content/uploads/2009/06/widget-frontend-double.png" target="_blank"><img src="http://jessealtman.com/wp-content/uploads/2009/06/widget-frontend-double-thumb.png" alt="Double Widget Front End"></a><br />
<br />
Double Widget &#8211; Back End<br />
<a href="http://jessealtman.com/wp-content/uploads/2009/06/widget-backend-double.png" target="_blank"><img src="http://jessealtman.com/wp-content/uploads/2009/06/widget-backend-double-thumb.png" alt="Double Widget Back End"></a><br />
<br />
Plugin Interface<br />
<a href="http://jessealtman.com/wp-content/uploads/2009/06/plugin-backend.png" target="_blank"><img src="http://jessealtman.com/wp-content/uploads/2009/06/plugin-backend-thumb.png" alt="Plugin Interface"></a><br />
</p>
<h2>Download</h2>
<p><a href="http://jessealtman.com/wp-content/uploads/2009/06/hello-world.zip">Download the Hello World Example</a></p>
<h2>Other Useful Resources</h2>
<ul>
<li><a href="http://codex.wordpress.org/Version_2.8#New_Widgets_API">WordPress Codex &#8211; WordPress 2.8 New Widget API</a></li>
<li><a href="http://codex.wordpress.org/Plugins/WordPress_Widgets_Api">WordPress Codex &#8211; Widgets API</a></li>
<li><a href="http://core.trac.wordpress.org/browser/trunk/wp-includes/widgets.php">WP_Widget source</a></li>
<li><a href="http://core.trac.wordpress.org/browser/trunk/wp-includes/default-widgets.php">Default WordPress Widget Code</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://jessealtman.com/2009/06/08/tutorial-wordpress-28-widget-api/feed/</wfw:commentRss>
		<slash:comments>46</slash:comments>
		</item>
	</channel>
</rss>
