Tutorial: Creating a Twitter Widget in WordPress

How to create a Twitter widget for WordPress.. Well not that there aren’t any plugins around, that already do that. Actually there are quite a few but wouldn’t it be nice to learn how to create one from scratch? And that’s the topic of my post today — I’ll show you how to create your very own WordPress widget to display your Twitter feed in your sidebar (or any other widgetized area, of course).

I’ll start off with a quick intro to creating a WordPress plugin, though embedding the Twitter widget in your theme functions.php file is not a bad idea either. After all, plugins and theme functions.php work alike in a lot of ways. I’ll then go quickly through the WordPress Widgets API and show you how to create your very first “Hello World” widget. Then I will extend the widget with some options for our Twitter badge and add the javascript on the front end. Sounds like a plan? So let’s get started!

Creating Your Plugin

I assume that you’ve dealt with WordPress code before, and have some solid PHP knowledge, as well as some general thoughts about how WordPress works, so you should know that your plugins live inside the plugins directory in your wp-content folder, and that’s where I’m going to work today.

You should also be familiar with the object-oriented concepts of PHP, since what I’ll be doing in a few seconds is called inheritance — extending the WP_Widget class to create my own Twitter widget. So get your code monkey glasses on and let’s get rolling with writing the plugin.

Create a new directory inside wp-content/plugins and call it my-twitter-widget and pump in a new empty text file called my-twitter-widget.php where you’ll be writing your code. Now, like every WordPress plugin, the main file starts with a plugin header:

/*
Plugin Name: My Twitter Widget
Plugin URI: (URL to your plugin website)
Description: Creates a Twitter profile widget for your sidebars.
Version: 1.0
Author: (your name goes here)
Author URI: [URL to your website]
License: GPLv2
*/

Don’t forget the opening php tag, and feel free to adjust the file header entries to whatever suits you best. Next, without closing the php tag, let’s dive into the WordPress Widgets API.

The WordPress Widgets API

Sidebars and widgets for WordPress have been around for quite some time now, and these days widgets are not limited to sidebars only, although they do inherit the “sidebar widgets” name from WordPress’ past. Keep in mind that widgets could be placed wherever you like on your page, as long as you define these “spots” in your template files.

Unless we need support for WordPress version prior to 2.8, we can go with simply extending the WP_Widget class to create our own widget, which turns out to be the easiest of all ways to create them. Quoting from the Widget API Codex entry, here’s the general structure of a WordPress widget:

class My_Twitter_Widget extends WP_Widget {
	function __construct() {
		// widget actual processes
	}

	function form( $instance ) {
		// outputs the options form on admin
	}

	function update( $new_instance, $old_instance ) {
		// processes widget options to be saved
	}

	function widget( $args, $instance ) {
		// outputs the content of the widget
	}

}
// Register the new widget
register_widget( 'My_Twitter_Widget' );

So let’s break that up into details for our Twitter widget. The __construct method is the class constructor (used to be My_Twitter_Widget function for PHP4 compatibility, but since WordPress 3.2 is dropping that, we should drop that too). The constructor usually does a simple parent call, but we’ll get to that later.

The form method, just like the comments in the code state, outputs the options form in the widget settings in the WordPress admin panel. This is where you get to squeeze in the Twitter widget options such as screen name, colors, sizes, etc. The current widget options will show up in the $instance variable passed in as an argument.

The update method is run when a widget is saved from the admin panel. This is our chance to do some input validation just before the options are saved. I won’t use this much in my code, but you have to be aware of it. The method has to return an instance, and you can use one of the two arguments passed along.

And the last but not least, widget method. This method is called when it’s time to actually draw (or render) the widget on screen (in your sidebar, footer, etc) so this method does the actual HTML output. The passed in $args variable is where the layout options are kept (before widget, after widget, before title, etc), while the $instance variable is where the widget options are passed along.

Creating Your First WordPress Widget

Let’s use the theory above to create a very simple WordPress widget that will print “Hello World” in our sidebar. Simple as that, with no options, no styling, just a message. You’ll also notice that multiple instances of the widget are automatically supported (thanks to WordPress).

class My_Twitter_Widget extends WP_Widget {
	function __construct() {
		parent::__construct(false, $name = 'Twitter Widget', array( 'description' => 'A shiny Twitter profile badge for your WordPress site.' ) );
	}

	function widget( $args, $instance ) {
		echo "Hello world!";
	}
};

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

As I mentioned earlier, the class constructor calls the parent class to register the widget and we can pass along a name and a description so that it pops up nicely in the admin area. The widget function simply says “Hello world!”. You might also have noticed that the actual register_widget call has been moved into the widgets_init action, right where it belongs. This is a best practice for themes and plugins development — fire your functions right where they belong, don’t just squeeze everything in during WordPress init!

Twitter Widget for WordPress

The result of the code above is nothing special, but you’ll see that in only a few lines of code you’ve managed to add an extra widget in the widgets section and you’re able to drag and drop that widget into one of your registered sidebars. On the front side of your website you’ll see that each placed Twitter widget simply prints “Hello world”, and now it’s time for some options.

Adding Some Widget Options

Let’s take a look at the Twitter profile widget and some of the preferences there. Twitter allows you to modify almost every aspect of the widget, but we’ll take only a few of those settings to our WordPress widget: user account, number of tweets to show and some color preferences.

As I mentioned earlier, all the widget options go inside the form method and here’s what it will look like when I add the screen name option:

function form( $instance ) {
	$screen_name = esc_attr( $instance['screen_name' ] );
	?>
		<label for="<?php echo $this->get_field_id( 'screen_name' ); ?>">Screen name:</label>
		<input id="<?php echo $this->get_field_id( 'screen_name' ); ?>" class="widefat" name="<?php echo $this->get_field_name( 'screen_name' ); ?>" type="text" value="<?php echo $screen_name; ?>" />
	<?php
}

You might be wondering what are the get_field_id and get_field_name methods. Well, those are just helper methods so you don’t need to worry about prefixing your ids, name collisions and so on. WordPress does that for you. The esc_attr is a sweet function that escapes the given values to use in attributes, such as the value attribute of our input field. So this form simply prints a label and a text field, for the end-users to put their Twitter name.

Twitter Widget Options

Go ahead and test it out. You won’t notice anything on the front side of your website, but the widgets area in the admin panel will now show you the option of entering a screen name. You can save the widget options, you can drag more widgets and have them have different screen names. Multi-instance, remember?

Before diving into how the widget will look on the front side and the javascript madness, let’s add up some more options to the widget so this is our final widget options form:

function form( $instance ) {
	$screen_name = esc_attr( $instance['screen_name'] );
	$num_tweets = esc_attr( $instance['num_tweets'] );
	$shell_background_color = esc_attr( $instance['shell_background_color'] );
	$shell_text_color = esc_attr( $instance['shell_text_color'] );
	$tweet_background_color = esc_attr( $instance['tweet_background_color'] );
	$tweet_text_color = esc_attr( $instance['tweet_text_color'] );
	$links_color = esc_attr( $instance['links_color'] );
	?>
	<p>
		<label for="<?php echo $this->get_field_id( 'screen_name' ); ?>">Screen name:</label>
		<input class="widefat" id="<?php echo $this->get_field_id( 'screen_name' ); ?>" name="<?php echo $this->get_field_name( 'screen_name' ); ?>" type="text" value="<?php echo $screen_name; ?>" />
	</p>
	<p>
		<label for="<?php echo $this->get_field_id( 'num_tweets' ); ?>">Number of Tweets:</label>
		<input class="widefat" id="<?php echo $this->get_field_id( 'num_tweets' ); ?>" name="<?php echo $this->get_field_name( 'num_tweets' ); ?>" type="text" value="<?php echo $num_tweets; ?>" />
	</p>
	<p>
		<label for="<?php echo $this->get_field_id( 'shell_background_color' ); ?>">Shell Background Color:</label>
		<input class="widefat" id="<?php echo $this->get_field_id( 'shell_background_color' ); ?>" name="<?php echo $this->get_field_name( 'shell_background_color' ); ?>" type="text" value="<?php echo $shell_background_color; ?>" />
	</p>
	<p>
		<label for="<?php echo $this->get_field_id( 'shell_text_color' ); ?>">Shell Text Color:</label>
		<input class="widefat" id="<?php echo $this->get_field_id( 'shell_text_color' ); ?>" name="<?php echo $this->get_field_name( 'shell_text_color' ); ?>" type="text" value="<?php echo $shell_text_color; ?>" />
	</p>
	<p>
		<label for="<?php echo $this->get_field_id( 'tweet_background_color' ); ?>">Tweet Background Color:</label>
		<input class="widefat" id="<?php echo $this->get_field_id( 'tweet_background_color' ); ?>" name="<?php echo $this->get_field_name( 'tweet_background_color' ); ?>" type="text" value="<?php echo $tweet_background_color; ?>" />
	</p>
	<p>
		<label for="<?php echo $this->get_field_id( 'tweet_text_color' ); ?>">Tweet Text Color:</label>
		<input class="widefat" id="<?php echo $this->get_field_id( 'tweet_text_color' ); ?>" name="<?php echo $this->get_field_name( 'tweet_text_color' ); ?>" type="text" value="<?php echo $tweet_text_color; ?>" />
	</p>
	<p>
		<label for="<?php echo $this->get_field_id( 'links_color' ); ?>">Links Color:</label>
		<input class="widefat" id="<?php echo $this->get_field_id( 'links_color' ); ?>" name="<?php echo $this->get_field_name( 'links_color' ); ?>" type="text" value="<?php echo $links_color; ?>" />
	</p>
	<?php
}

As you can see, I’ve added the rest of the items the same way I added the screen name input. They’re simple text inputs so in in the admin side it will now look like this:

Twitter Widget More Options

Of course I populated the form with some demo data for illustration purposes, yours will probably be empty. You can try playing around with the form, and you’ll see again that the values are saved and restored whenever needed, multiple widgets are supported and you can drag the widget from one sidebar to another. But hey, the front side of it still says “Hello world!”. Relax…

Rendering the Twitter Profile Widget

Now that you’ve finalized your admin form, it’s time to get working on the widget method, which does the actual output of whatever has been configured. Now remember I told you about the $args variable which will hold the layout settings? Well you’re gonna use only two of those arguments — before_widget and after_widget. Normally you’d use all of them, but since our Twitter profile widget initially comes with a nice looking heading, let’s skip the title part.

With that in mind, here’s how the widget function will look like:

function widget( $args, $instance ) {
	echo $args['before_widget'];
	?>
	<!-- The Twitter javascript will go here -->
	<?php
	echo $args['after_widget'];
}

The widget options that are set in the admin side are all in the $instance variable which is also passed in to the widget method. It’s a PHP array so you can access the values by their keys. WordPress will take care of creating those keys for you when saving the widget options in the admin. Just to be clear, this is how you output the screen name in the widget:

echo $instance['screen_name'];

Of course we’ll have more than the screen name in the widget output, so here’s the final code, containing the screen name, the tweets count and all the color settings that the user has provided in the widget options:

function widget( $args, $instance ) {
	echo $args['before_widget'];
	?>
	<script src="http://widgets.twimg.com/j/2/widget.js"></script>
	<script>
	new TWTR.Widget({
	  version: 2,
	  type: 'profile',
	  rpp: <?php echo $instance['num_tweets']; ?>,
	  interval: 6000,
	  width: 'auto',
	  height: 300,
	  theme: {
	    shell: {
	      background: '<?php echo $instance['shell_background_color']; ?>',
	      color: '<?php echo $instance['shell_text_color']; ?>'
	    },
	    tweets: {
	      background: '<?php echo $instance['tweet_background_color']; ?>',
	      color: '<?php echo $instance['tweet_text_color']; ?>',
	      links: '<?php echo $instance['links_color']; ?>'
	    }
	  },
	  features: {
	    scrollbar: false,
	    loop: false,
	    live: false,
	    hashtags: true,
	    timestamp: true,
	    avatars: false,
	    behavior: 'all'
	  }
	}).render().setUser('<?php echo $instance['screen_name']; ?>').start();
	</script>
	<?php
	echo $args['after_widget'];
}

You’ll notice that most of the Javascript stuff is taken from the Twitter profile widget generator where we simply substitute some of the values to override with the ones set in our own widget’s settings. If you’ve done everything correctly, try dropping a Twitter widget into your sidebar, configure the colors and check it out, should look something like this:

Twitter Widget in Action

Just a note about styling the widget. The CSS of your WordPress theme may do some damage, most probably to the first two lines of the Twitter widget. I’ve seen this happen in four or five different themes, and it’s caused by the fact that the Twitter widget uses the h3 and h4 tags to render the name and the screen name for the profile. The heading tags usually get a clear: both; rule so they’re pushed below the user image in the widget. But this can easily be fixed from your stylesheet:

.twtr-hd h3, .twtr-hd h4 {
	clear: none;
}

And you might want to add an !important modifier there if you’re still experiencing trouble. Oh well, that’s about it! Congratulations!

Recap & Conclusion

So in this tutorial I’ve shown you how to create your very own Twitter widget based on the official Twitter profile widget. I gave you an introduction to the WordPress Widgets API, the main methods that should be used. This wasn’t a definitive guide, but you should get a clear picture of how WordPress widgets are handled behind the scenes.

I went through creating the widget options form and throwing variables around on the front side of your website to create the actual javascript widget. I didn’t touch the security side of it though, and if you’re planning a production plugin then you should. Like what would happen if I entered some special symbols instead of the screen name? Or a non-valid HTML color code, or a couple million number of tweets?

Along with the security matters, you might also want to enhance your widget settings form a little bit, like create a counter where I could hit the up/down arrows for the number of tweets. Create popup color pickers for the HTML color code values. And of course implement the rest of the options available in Twitter’s original widget.

If by any chance you weren’t able to get your code working, you can always download the full source file for this tutorial, compare and figure out where you (or I) went wrong.

Hope you had fun learning and I’ll see you again soon, with some more cool WordPress tutorials. Subscribe to our RSS feed and follow us on Twitter to make sure you get the latest and most awesome tutorials, screencasts, news and updates about WordPress and more!