Skip to content

How to write a simple Twitter widget for WordPress

Being as hip as I am, I have been active on Twitter since long before Oprah. Days before Oprah even. As I also have a WordPress blog, I thought it would be nice to add a small widget to the sidebar that displays my last few updates on Twitter. WordPress supports a large number of plugins, many of which handle Twitter updates, but there are so many and they all do so much that it was hard to choose. As I’d been meaning to look into the WordPress plugin mechanism anyway and as it is very easy to generate a Twitter box, I thought I’d have a go at writing a simple plugin myself and document the process. At the end of this post I have also collected some useful links.

Step 1 – Create the main file for the plugin

Each plugin requires at least a main php file, which goes in the wp-content/plugins directory. You can find a bare version of this file here. For now, this file mainly consists of comments which describe the plugin and specify the license under which it is published. See the plugin tutorial at WordPress for more information on these. The only interesting bit is the PHP code at the end:
function init_simple_twitter_box()
{
...
}
add_action('plugins_loaded', 'init_simple_twitter_box');
This code register the function init_simple_twitter_box to be called when the plugins have been loaded. It is this function that will define the widget.

Install the plugin

The code above is all that is required to create a plugin, albeit one that does nothing. To see that it actually works, you can install the plugin. To do this, put the PHP file in the  ‘wp-content/plugins’ directory (or a subdirectory of that directory). Now, go to the ‘Plugins’ page in your WordPress administration interface. You should see the plugin with information  you entered in the PHP file’s header. Now click ‘Activate’ to use enable the plugin.

If you’re going to do a lot of WordPress development, it may be worthwhile to set up a development instance of WordPress, which you can modify without breaking your blog. I am running one on my laptop using wampserver. See this page for more information.

Step 2 – Create the widget

Now that the plugin is installed, it is time to make it do something useful. To create the actual widget, simply register a function that will create the HTML for widget:

function init_simple_twitter_box()
{
    function widget_simple_twitter_box($args)
    {
        // Generate HTML
    }

    wp_register_sidebar_widget('widget_simple_twitter_box',
                               __('SimpleTwitterBox'),
                               'widget_simple_twitter_box',
                               array('description' => __('Displays the last few tweets of your Twitter feed')));
}

The function wp_register_sidebar_widget does all the work. It expects a widget id, which must be unique, so I have included the name of the plugin. The second parameter is the name of the plugin. The function __() means that the name may be translated. See Translating WordPress for more details. The third parameter is the name of the function that will generate the widget’s HTML. The final parameter is an array containing some options. I have just set the description; notice how once again the string that will be shown to the user is passed throught the __() function for possible translation.

Note how the function widget_simple_twitter_box is defined inside init_simple_twitter_box. This is a simple way to group all the functions for the widget together.

Install the widget

The code above is already enough to install the widget. To do this, go to the administration interface again and go to the page ‘Appearance > Widgets’. You should see your widget listed there with the description you provided. Click ‘Add’ to add it to your sidebar. If you now go to your blog, you will see … nothing. That is because the widget does not generate any HTML yet, which is the next step.

Step 3 – Generate actual HTML

Now it is time to actually generate some HTML so the widget will show up. For this, implement the function widget_simple_twitter_box, filling in your username on Twitter.

function widget_simple_twitter_box($args)
{
    extract($args); // Make before_widget, etc available.
    $username = <your twitter username>;
    $number_of_tweets = 5;
    // Generate HTML
    ?>
        // WordPress support call
        <?php echo $before_widget; ?>

        // Twitter code
        <div id="twitter_div">
            <ul id="twitter_update_list"></ul>
        </div>
        <script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
        <script type="text/javascript" src="http://twitter.com/statuses/user_timeline/<?php echo $username?>.json?callback=twitterCallback2&amp;count=<?php echo $number_of_tweets?>"></script>

        // Wordpress support call
        <?php echo $after_widget; ?>
    <?php
}

This function sets up some parameters (which we’ll get from options later) and renders some HTML. There are two parts to this: the WordPress code that generates the HTML for the widget’s frame (see the WordPress API documentation for more details) and the Twitter code that renders the actual updates. The Twitter code is simply the code generated for a Twitter badge.

So, that’s it. When you visit your site, you’ll see a Twitter badge in your sidebar! Of course, this is not a full WordPress plugin yet, for that some more work is required.

Step 4 – Make the widget configurable

For the widget to be useful to other people, at least the Twitter username should be configurable. To do this, you can create an options form. This form can be accessed by clicking on the widget’s  ‘Edit’ link, which can be found on the ‘Appearance > Widgets’ page in the administration interface.

To create the form, once again register a WordPress callback, using register_widget_control. This takes two parameters, the widget id (which must match the one supplied to wp_register_sidebar_widget) and the function name.

function widget_simple_twitter_box_control($args)
{
    // Get access to the options array for the plugin
    $options = get_option('widget_simple_twitter_box');

    // Set default options if no options are specified yet
    if ( !is_array($options) )
        $options = array('username'=>'');

    // Store the options if the form is submitted
    if ( $_POST['widget_simple_twitter_box_submit'] )
    {
        $options['username'] = strip_tags(stripslashes($_POST['widget_simple_twitter_box_username']));
	    update_option('widget_simple_twitter_box', $options);
    }

    // Get the options into variables, escaping html characters on the way
    $username = htmlspecialchars($options['username'], ENT_QUOTES);

    // Render the form.
    // A <form> tag is not required, WordPress has already done that.
    // Note the hidden input at the end, which is used to detect if the form is being submitted
    ?>
        <p style="text-align:right;">
            <label for="widget_simple_twitter_box_username">
                <?php echo __('Username:')?>
            </label>
            <input style="width: 150px;" type="text" id="widget_simple_twitter_box_username"
		    name="widget_simple_twitter_box_username" value="<?php echo $username?>" />
        </p>

        <input type="hidden" id="widget_simple_twitter_box_submit" name="widget_simple_twitter_box_submit" value="1" />
    <?php
}

register_widget_control('widget_simple_twitter_box', 'widget_simple_twitter_box_control');

Apart from accessing the WordPress options, this is an HTML form like any other. The function widget_simple_twitter_box_control is generally invoked twice: once to render the form and once to handle submission of form. The difference is detected using the hidden input widget_simple_twitter_box_submit, which is present only when the form is submitted.

Using the preferences in the widget

To actually use the preference instead of the hard coded username, simply modify the function widget_simple_twitter_box:

function widget_simple_twitter_box($args)
{
    extract($args);
    $options = get_option('widget_simple_twitter_box');
    $username = htmlspecialchars($options['username'], ENT_QUOTES);
     ...

For a real plugin, you’ll likely have more preferences, but they all work the same in principle.

Step 5 – Package and publish the plugin

If you just want to publish your plugin, you can just zip it up and post it on your site. However, you’ll generally want to make your plugin available through the WordPress plugin directory. To do this, you have to host your plugin in the WordPress svn repository. You can sign up for an account here. You’ll also have to add a readme.txt to your plugin. The Plugin Developer Center has all the information you need.

Links

  • Reddit
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Digg
  • LinkedIn
  • StumbleUpon

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*