How to Create an Advanced Twitter Widget

As of March 2011, the current average number of "Tweets" the world sends per day is 140 million. This tutorial demonstrates how to create a custom Twitter widget from scratch that uses the Twitter API, Web Intents and @Anywhere. Using the Twitter platform to create a fun, interactive tool for your website can be beneficial both in the learning and promotion departments!


A Few Pros and Cons

Pros:

  • Greater Customization than the default Twitter widget.
  • Cache file prevents problems with Twitter API Rate Limiting and over capacity issues

Cons:

  • Requires Twitter oAuth if you want to incorporate the advanced functionality of @Anywhere
  • Setting up a Cron Job can be tricky (there are many web hosting server configurations and control panels)

Now, lets get started!


Step 1. Markup and Styling

This tutorial assumes that you have some CSS and HTML knowledge, and starts out with the basic markup and styling for the widget. Note that the content of the widget is located in <div id="tweet"></div> and is created using jQuery, Twitter API and PHP.

The HTML

The CSS

The #content ID may need to be changed based on your theme and placement of the widget (Ex. #content, #sidebar, #footer)


Step 2. PHP "Cache File" Script

As of this writing, the Twitter limit for Unauthenticated API calls is 150 requests per hour. OAuth calls are permitted at 350 requests per hour and are measured against the oauth_token used in the request.

To ensure that our custom Twitter widget does not run into problems with Twitter API rate limiting, a PHP "cache file" script needs to be created. This script retreives the Twitter API "GET statuses/user_timeline" information and stores it in a "TXT" file located in the cache directory on your server.

If you do not already have a cache directory, you will need to create one. You will also need to create a directory on your server for the PHP cache file script.

Create a PHP file that contains the following code.

The "count=3" portion of the code controls how many "tweets" will be displayed in your Twitter widget. If you want to display only one tweet, then change the code to "count=1".

Note that the "&include_rts=true" needs to be included if you want your Twitter widget to display "retweets". Visit the Twitter API doumentation "GET statuses/user_timeline" for more information and available options.


Step 3. Set Up Cron Job

Next, a Cron job needs to be created that executes the PHP script at a set number of times per hour. How the Cron job is set up depends on your web hosting control panel. Please refer to "Scheduling Tasks with Cron Jobs" for an in depth tutorial.

Below is an example of Cron tab settings for a Plesk control panel that runs a Cron job (4) times per hour (every fifteen minutes), every day.

  • Minute = */15
  • Hour = *
  • Day of the Month = *
  • Month = *
  • Day of the Week = *
  • Command = /usr/bin/curl -s http://your_domain.com/twitter-widget/twitter-cron.php > /dev/null

Step 4. Add jQuery and Twitter Web Intents Script Tags

We need to make sure that our web page references the jQuery library. For this tutorial, the jQuery library is included through the use of the jQuery CDN.

Between the head tags of your web page add

In addition to using the Twitter API, the Twitter widget uses Twitter Web Intents to add "Retweet", "Reply" and "Favorite" functionality.

Just below the jQuery script tag, add


Step 5. The jQuery Code

An external JavaScript file, "twitter-widget.js," needs to be created. This JavaScript file contains the jQuery code that generates the "content" of the Twitter widget. The jQuery code retreives the Twitter API information from the cache file that was created by the PHP script in Step two.

In the JS file, add the following jQuery code.

jQuery .getJSON() is used to load the JSON-encoded data from the cache TXT File. Using jQuery .append(), the content is displayed through the <div id="tweet"></div> of the XHTML markup. Each Twitter API item is prefixed with "item.". The Twitter API items used in the jQuery code are:

  • text (item.text) - The text of each tweet
  • created_at (item.created_at) - The date each tweet was posted
  • id_str (item.id_str) - The unique ID number of each tweet

Editor's Note: If you'd prefer to get that muddy HTML out of your JavaScript, consider using the jQuery templating plugin.


Step 6. Converting Twitter Time Stamp to Relative Time (Time Ago)

The data that is retrieved using the Twitter API is "raw" data and needs to be fixed up for the Twitter widget.

In the twitter-widget.js file, below the jQuery code, add the following JavaScript code.

This code converts the Twitter Time stamp to relative time, such as "3 hours ago."


Step 7. Creating Workable Anchor Links

In the twitter-widget.js file, below the convert timestamp code, add the following JavaScript code.

When using the Twitter API, the links contained in Twitter posts are displayed in text format only, not workable anchor links. The above code converts standard URL text only links into workable anchor links.


Step 8. Adding Advanced Features Using Twitter @Anywhere

We have now created a rather neat, custom Twitter widget that includes some basic user interactivity. But what if we want to add really cool, advanced functionality to our Twitter widget? Thanks to the Twitter @Anywhere Service, we can accomplish this fairly easily.

Sign up for the Twitter @Anywhere Service at https://dev.twitter.com/apps/new.

Create a New "App" and complete the steps of the online registration process. Visit this article for detailed help on completing the registration process.

"The callback URL property (Set in your @Anywhere account) of your application must match both the subdomain and domain of the web application utilizing @Anywhere. "

The next few steps of this tutorial explain how to add Twitter @Anywhere advanced functionality.


Step 9. Add @Anywhere Script Tag

As close to the top of the web page as possible, add the @Anywhere script Tag:

Note that your Twitter oAuth Consumer Key needs to be added to the script tag.


Step 10. User Login and Authorization

Certain features of the Twitter @Anywhere service do not require the user to be logged into Twitter. Hover Cards and Auto-linkification of Twitter usernames as examples. However, most @Anywhere features DO require the user to login and authorize your site for access. The "Connect with Twitter" button allows users to authenticate securely with Twitter.

Below <div id="tweet"></div>, add the following code.

Now, create an external JavaScript file "twitter-login.js" containing the following code.


Step 11. Determining the Connected State

@Anywhere provides several ways of determining whether a user is already logged into Twitter and has already granted your application authorization for access. For this tutorial, we are going to use authComplete and signOut events.

Just below the web page <body> tag, add the following:

By adding the above code, the authComplete and signOut events are now triggered by ANY @Anywhere functionality.


Step 12. Adding Hovercard Functionality

A Hovercard displays data about a Twitter user in a tooltip and also includes a follow/unfollow button.

To add a hovercard that is "expanded" by default, add the following code below the authComplete and signOut code, just below the web page <body> tag:

Note that if you add Hovercard functionality, the Auto-linkification of Twitter usernames is also added by default. This makes adding the "T.linkifyUsers()" function to your webpage unnecessary.


Step 13. Adding a Follow Button

To add a Twitter follow button to the widget, below <div id="tweet"></div>, add the following code.

Note that you need to add your Twitter screen name to the above code.


Step 14. Adding a Tweet Box

If you would like to add a Tweet Box instead of a follow button, below <div id="tweet"></div> add the following code.


All Done!

View the completed demo. Creating a Twitter driven widget from scratch that uses the Twitter API, Web Intents and @Anywhere takes a bit of work. However, you can create something interactive and fun for visitors of your website!

Please note that the JavaScript codes for Relative Time and Creating Workable Anchor Links are thanks to this article.

For those of you who would rather create a basic Twitter driven widget without using Twitter oAuth and @Anywhere, there are basic demos included in the source files zip. There are also two demos that display Twitter profile images next to each tweet.

If you have any questions about this tutorial, please ask them using the "Add a Comment Box" below.

Tags:

Comments

Related Articles