Tutorials

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

Written by Kevin Liew on 12 Apr 2016
117,132 Views • Shares
136 comments

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 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
vincent 3 years ago
not working!!!!
Reply
Kevin Admin 6 months ago
Okay, I finally updated this article :)
Reply
Rich 5 months ago
Excellent! I found a bug though:

When appending tweets to the page in the success of the ajax call, the for loop doesn't reference the JQTWEET.numTweets definition!

Thanks for the awesome script!
Reply
Grace 5 months ago
I feel quite stupid but I can't get this to work at all. I am getting errors when I try to view the tweets.php page, e.g. "Notice: Undefined index: q", and the same for 'count' and 'api'. Am I missing something very obvious here? Would appreciate any help you can give me!
Reply
Francois 4 months ago
Thanks for the article!

I just had one issue with a deprecated Jquery IE detection. I replaced it with the new Jquery browser detection in "twitter.js" and works fine.

Old code:


if ($.browser.msie) {
// IE can't parse these crazy Ruby dates
then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
}


New one::


if(navigator.userAgent.toUpperCase().indexOf('MSIE') >= 0) {
// IE can't parse these crazy Ruby dates
then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
}


Hope this helps!
Reply
jitendra 4 months ago
NIce Script Its Working
Reply
Mark 3 months ago
Is t possible to refresh the request at a set period and prepend any new tweets to the page rather than refreshing the whole page?
Reply