MandalaTV
Personal and Professional Blog of Rich Hauck

Displaying Your Last Tweet on Your Website

by: Rich Hauck

It used to be that you could anonymously make Twitter API requests to display your last tweet on your website using just Javascript, but with Twitter’s retirement of its v1 API, those days are gone.

If you’re just looking to display a particular tweet you can find out how to embed a tweet on Twitter’s Developer site. If you’d rather avoid all the extra chrome that comes with it, though, then you’ll need to use their new API (v1.1 as of this writing) and a server-side language.

I don’t display my last tweet on this site (outside of the widget to the right), but I did have to go through the process for a client using PHP. Here’s the steps:

  1. Log into https://dev.twitter.com/apps with your Twitter account.
  2. Click the “Create a new application” button.
  3. Fill out the name, description, and website fields. The name should uniquely identify your “app” (something like “mywebsite.com latest tweet” will suffice). The website and callback URL should be identical. Agree to terms.

    Create Application Page

  4. Make note of:
    • oauth_access_token
    • oauth_access_token_secret
    • consumer_key
    • consumer_secret

    as you’ll need these in your script.

  5. As I said, you’ll need to go server-side on this one, but fortunately, J7mbo kindly posted a simple PHP wrapper for Twitter API v1.1 calls. Download it and check out the documentation.
  6. Create a PHP page next to the TwitterAPIExchange.php file you downloaded from GitHub and paste the following code into it:
    <?php
    require_once('TwitterAPIExchange.php');
    function get_last_tweet(){
    	/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
    	$settings = array(
    	    'oauth_access_token' => "xxxxxxxxxxxx",
    	    'oauth_access_token_secret' => "xxxxxxxxxxxx",
    	    'consumer_key' => "xxxxxxxxxxxx",
    	    'consumer_secret' => "xxxxxxxxxxxx"
    	);
    	/** Perform a GET request and echo the response **/
    	/** Note: Set the GET field BEFORE calling buildOauth(); **/
    	$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
    	$getfield = '?screen_name=xxxxxxxxxxxx&count=1';
    	$requestMethod = 'GET';
    	$twitter = new TwitterAPIExchange($settings);
    	$json = $twitter->setGetfield($getfield)
    	             ->buildOauth($url, $requestMethod)
    	             ->performRequest();
    
    	$json = json_decode($json);
    
    	// the rest of the script just parses through the data,
    	// namely the date and time of tweet and any 'entities'
    	// Borrowed from http://snipplr.com/view/54710/
    	if (!empty($json)) :
    		foreach ($json as $tweet) :
    			$datetime = $tweet->created_at;
    			$date = date('M d, Y', strtotime($datetime));
    			$time = date('g:ia', strtotime($datetime));
    			$tweet_text = $tweet->text;
    
    			// check if any entities exist and if so, replace then with hyperlinked versions
    			if (!empty($tweet->entities->urls) || !empty($tweet->entities->hashtags) || !empty($tweet->entities->user_mentions)) {
    				foreach ($tweet->entities->urls as $url) {
    					$find = $url->url;
    					$replace = '<a href="'.$find.'">'.$find.'</a>';
    					$tweet_text = str_replace($find,$replace,$tweet_text);
    				}
    				foreach ($tweet->entities->hashtags as $hashtag) {
    					$find = '#'.$hashtag->text;
    					$replace = '<a href="http://twitter.com/#!/search/%23'.$hashtag->text.'">'.$find.'</a>';
    					$tweet_text = str_replace($find,$replace,$tweet_text);
    				}
    				foreach ($tweet->entities->user_mentions as $user_mention) {
    					$find = "@".$user_mention->screen_name;
    					$replace = '<a href="http://twitter.com/'.$user_mention->screen_name.'">'.$find.'</a>';
    					$tweet_text = str_ireplace($find,$replace,$tweet_text);
    				}
    			}
    		endforeach;
    		endif;
    		return $tweet_text;
    }
    echo get_last_tweet();
    ?>
    
  7. Replace xxxxxxxxxxxx with your respective token, key, and secrets from dev.twitter.com. Replace the screen_name value with your Twitter account name.

While the TwitterAPIExchange will make the request for you, the return value from Twitter’s API is just a text string with no embedded links. What this means is that if a URL or hashtag was tweeted, it won’t be linked up. Fortunately, I pulled part of a script I found on Snippet¬†(L23-53, above)¬†that parses the JSON object returned by Twitter’s API and replaces any hyperlinks.

Enjoy.


Categories:socialnetworks webdesign
Tags:javascript json php
Comments: 2

2 thoughts on “Displaying Your Last Tweet on Your Website

Leave a Reply

Your email address will not be published. Required fields are marked *

About Rich Hauck

Rich Hauck

I'm a creative technologist at Hauck Interactive, Inc. and an adjunct instructor at HACC. I live in Harrisburg, Pa. with my wife and three boys. I enjoy good coffee, Trappist beers, Orioles baseball, and good design.


Archives