Create A Dead Simple Twitter Feed with jQuery + PHP + OAuth (Updated)

Written by Kevin Liew on 12 Apr 2016
193,379 Views • Tutorials

In this tutorial, we will be creating a jQuery script that retrieve twitter tweets from user account. It's quick and easy, come with link, hash tag, alias parser as well as time posted (calculated relatively). Most importantly, everything has a class and will be flexible to style and match your design!

This is an old post that I created long time ago, but it hasn't been updated ever since Twitter moved on from the old API. Now I decided to spend some time to fine tune it and added a layer of PHP with OAuth authentication to retrieve tweets. I also added the capability to display media for the tweet.

To retrieve tweets from user timeline, we will be using statuses/user_timeline public API from Twitter. To make the OAuth authentication painless, we're using this third party PHP-Twitter API wrapper caled Twitter for PHP.

You will need to sign in to the Twitter and register an application from the Twitter App page to get teh required consumer keys and access tokens. Remember to never reveal your consumer secrets. Click on My Access Token link from the sidebar and retrieve your own access token. Now you have consumer key, consumer secret, access token and access token secret.

We will use links/hashtag/alias script to format Tweet's hashtag, aliases. This is the screenshot of text and image tweets:

HTML

We need a simple HTML layout, linked with jQuery framework and twitter script. Also, a div with id called "jstwitter" - we will be appending all tweets from twitter server, processed it and chuck it inside.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
	<title></title>
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
	<script src="twitter.js"></script>
</head>
<body>
	
	<div id="jstwitter">
	</div>
	
</body>
</html>

CSS

We made a quick and clean layout. However, you can style the following elements:

  • .twtr-hashtag: #abc
  • .twtr-hyperlink: hyperlink
  • .twtr-atreply: #abc
  • .time: relative time (10 minutes ago)
body {
  background:#bae0f6;
  font-size:14px;
  font-family: 'Helvetica', arial, sans-serif;
}

* {
  -webkit-box-sizing:border-box;
  -moz-box-sizing:border-box;
  box-sizing:border-box;
}

#jstwitter {
	width: 300px;
	font-size: 15px;
	color: #333333;
  margin: 0 auto;
  text-align:center;
}

#jstwitter .tweet {
	margin: 0 auto 15px auto;
	padding: 15px;
	border-radius:3px;
  background:#ffffff;
  text-align:left;
  box-shadow: 0 0 2px 1px rgba(0,0,0,0.1);
}

#jstwitter .tweet a {
	text-decoration: none;
	color: #13c9d0;
}

#jstwitter .tweet a:hover {
	text-decoration: underline;
}

#jstwitter img {
  display:block;
  margin-bottom:5px;
  max-width:100%;
}

#jstwitter .tweet .time {
	font-size: 10px;
	font-style: italic;
	color: #666666;
  display:block;
  margin-top:3px;
}

Javascript

Alright, javascript. We will divide it into 3 sections:

  • loadTweets: This is how we retrieve tweets. We use AJAX to call a PHP Twitter API wrapper which will return data in JSON format. This function retrieves and processes it.
  • timeAgo: Relative calculator from twitter.
  • ify: Convert twitter hashtag, alias, and links into hyperlinks.
JQTWEET = {
	
	// Set twitter username, number of tweets & id/class to append tweets
	user: 'quenesswebblog',
	numTweets: 5,
	appendTo: '#jstwitter',

	// core function of jqtweet
	loadTweets: function() {
		$.ajax({
			url: 'tweets.php',
			type: 'post',
			dataType: 'json',
			data: {
				q: JQTWEET.user,
				count: JQTWEET.numTweets,
        api: 'statuses/user_timeline'
			},
			success: function(data, textStatus, xhr) {

        var html = '<div class="tweet">TWEET_IMGTWEET_TEXT<div class="time">AGO</div>';

				// append tweets into page
				for (var i = 0; i < data.length; i++) {
          
					$(JQTWEET.appendTo).append(
						html.replace('TWEET_TEXT', JQTWEET.ify.clean(data[i].text))
							.replace(/USER/g, data[i].user.screen_name)
							.replace('AGO', JQTWEET.timeAgo(data[i].created_at))
							.replace(/ID/g, data[i].id_str)
              .replace('TWEET_IMG', (data[i].entities.media && data[i].entities.media.length ? '<img data-src="' + data[i].entities.media[0].media_url + '"/>': ''))
					);

				}					
			}	

		});
		
	}, 
	
		
	/**
      * relative time calculator FROM TWITTER
      * @param {string} twitter date string returned from Twitter API
      * @return {string} relative time like "2 minutes ago"
      */
    timeAgo: function(dateString) {
		var rightNow = new Date();
		var then = new Date(dateString);
		
		if ($.browser.msie) {
			// IE can't parse these crazy Ruby dates
			then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
		}

		var diff = rightNow - then;

		var second = 1000,
		minute = second * 60,
		hour = minute * 60,
		day = hour * 24,
		week = day * 7;

		if (isNaN(diff) || diff < 0) {
			return ""; // return blank string if unknown
		}

		if (diff < second * 2) {
			// within 2 seconds
			return "right now";
		}

		if (diff < minute) {
			return Math.floor(diff / second) + " seconds ago";
		}

		if (diff < minute * 2) {
			return "about 1 minute ago";
		}

		if (diff < hour) {
			return Math.floor(diff / minute) + " minutes ago";
		}

		if (diff < hour * 2) {
			return "about 1 hour ago";
		}

		if (diff < day) {
			return  Math.floor(diff / hour) + " hours ago";
		}

		if (diff > day && diff < day * 2) {
			return "yesterday";
		}

		if (diff < day * 365) {
			return Math.floor(diff / day) + " days ago";
		}

		else {
			return "over a year ago";
		}
	}, // timeAgo()
    
	
    /**
      * The Twitalinkahashifyer!
      * http://www.dustindiaz.com/basement/ify.html
      * Eg:
      * ify.clean('your tweet text');
      */
    ify:  {
      link: function(tweet) {
        return tweet.replace(/\b(((https*\:\/\/)|www\.)[^\"\']+?)(([!?,.\)]+)?(\s|$))/g, function(link, m1, m2, m3, m4) {
          var http = m2.match(/w/) ? 'http://' : '';
          return '<a class="twtr-hyperlink" target="_blank" href="' + http + m1 + '">' + ((m1.length > 25) ? m1.substr(0, 24) + '...' : m1) + '</a>' + m4;
        });
      },

      at: function(tweet) {
        return tweet.replace(/\B[@ï¼ ]([a-zA-Z0-9_]{1,20})/g, function(m, username) {
          return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/intent/user?screen_name=' + username + '">@' + username + '</a>';
        });
      },

      list: function(tweet) {
        return tweet.replace(/\B[@ï¼ ]([a-zA-Z0-9_]{1,20}\/\w+)/g, function(m, userlist) {
          return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/' + userlist + '">@' + userlist + '</a>';
        });
      },

      hash: function(tweet) {
        return tweet.replace(/(^|\s+)#(\w+)/gi, function(m, before, hash) {
          return before + '<a target="_blank" class="twtr-hashtag" href="http://twitter.com/search?q=%23' + hash + '">#' + hash + '</a>';
        });
      },

      clean: function(tweet) {
        return this.hash(this.at(this.list(this.link(tweet))));
      }
    } // ify

	
};



$(document).ready(function () {
    // start jqtweet!
    JQTWEET.loadTweets();
});

PHP

Ever since Twitter moved on from REST 1.0, the most secure implementation if using server-side language because you need to specify consumer key, consumer secret key and access tokens. You need to be authenticated in order to access the API too. Thankfully, there's a lot of PHP library available to make this simple.

We're going to use Twitter for PHP. Here's the source for PHP side, a very simple implementation:

<?php

require_once 'twitter-php/twitter.class.php';

//Twitter OAuth Settings, enter your settings here:
$CONSUMER_KEY = '...';
$CONSUMER_SECRET = '...';
$ACCESS_TOKEN = '...';
$ACCESS_TOKEN_SECRET = '...';

$twitter = new Twitter($CONSUMER_KEY, $CONSUMER_SECRET, $ACCESS_TOKEN, $ACCESS_TOKEN_SECRET);

// retrieve data
$q = $_POST['q'];
$count = $_POST['count'];
$api = $_POST['api'];

// api data
$params = array(
	'screen_name' => $q,
	'q' => $q,
	'count' => 20,
  'includes_rts' => true
);

$results = $twitter->request($api, 'GET', $params);

// output as JSON
echo json_encode($results);
?>

Conclusion

No doubt, twitter is one of the hottest social media, so I hope this tutorial will able to help you to display your own tweets in your website. If you like it, please help me to spread it :) Thanks!

Demo Download
Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

136 comments
Eric 12 years ago
This is awesome, thank you so much.

Anyway I can display ... reply, retweet, favorite under each entry ?

Thanks again for this awesome tutorial!
Reply
Kevin Liew Admin 12 years ago
Change this:
var html = '<div class="tweet">TWEET_TEXT<div class="time">AGO</div>';

To:

var html = '<div class="tweet">TWEET_TEXT<div class="time">AGO</div><div class="details">AGO - <a href="http://twitter.com/intent/tweet?in_reply_to=ID">reply</a> - <a href="http://twitter.com/intent/tweet?in_reply_to=ID">reply</a> - <a href="http://twitter.com/intent/tweet?in_reply_to=ID">reply</a>

It should work.
Reply
Staffan Estberg 12 years ago
Nice script! But it doesn't seem to be working in IE (tested in 7+8) if I have posts that are less than one day old. Ideas on how to solve this?
Reply
Kevin Liew Admin 12 years ago
Tested it on 8, it works. Im pretty sure they work because I tested it on those platforms before.
Reply
Jeffrey 12 years ago
I can not seem to get this to display online. however shows up correctly locally.
Reply
Kevin Liew Admin 12 years ago
Use firebug and make sure are your js, jquery are linked properly.
Reply
john emmett 12 years ago
Hi i'm using Jquery 1.7.2 and when i try and add your tweeter it doesnt want to show anything. I add the your Jquery file 1.6.1 and it works but my other Jquery apps don't wanna work. Any help to get this to work with Jquery 1.7.2?
Reply
Kevin Liew Admin 12 years ago
Can you check the console to see if there any errors? Theoretically, this script just use the common jQuery method, it should work.
Reply
Deepak 12 years ago
HI!
Thanks for this excellent plugin. I am not wuite familiar with Java. I want user to input user ID through php form. How can I declare php variable in javascript. If not what is the other alternative.
What I exactly want to do is echo out php variable like below:

<?php echo $option['twitter_id']; ?>
Reply
Dan 12 years ago
Thank you!
Reply
Richard 12 years ago
Hi - love the script - very simple to get working. My question is can we strip out RT's from the feed?

Thanks.
Reply
Umair 12 years ago
great work Kevin Liew
Reply
Kevin Liew Admin 12 years ago
You can append this after line 30 in the js code:

.replace(/RT/g, '')
Reply
David 12 years ago
A great script! Thanks. Is it possible to show Tweets that include your Twitter name too ? So that you can see the conversation as such. Thanks in advance.
Reply
sxvs 12 years ago
Can I hide the conversations / @reply ?
include_replies: false?
Reply
Wijnand 12 years ago
Thanks a lot!

Is there an easy way to shuffle the tweets?
Reply
David 12 years ago
If tweets have external links, it doesn't show hyperlink on the page. It is probably stripping the tags from the HTML which include the <a> tags. Any help?
Reply
Graham Sanders 12 years ago
Hi Kevin,

As of 17 March 2012 the Twitter feed no longer seems to work (perhaps something to do with the external file?)
Reply