Tutorials

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

Written by Kevin Liew on 12 Apr 2016
142,818 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
Duane 6 years ago
Thanks for this... works like a charm
Reply
Winnie 6 years ago
This tutorial is very supportive ! Awesome ! Could you tell me how can I put user's profile image in this code.
Big Thanks !!
Reply
Charles 6 years ago
FINALLY! A feed script that works.
Thank you.
Reply
Mike 5 years ago
Great script! worked first time. Thanks. What version of the API does this use? When i was still trying to figure it out for myself i noticed version 1 will stop working at some point soon. https://dev.twitter.com/docs/api
Reply
Muhammad Naeem 5 years ago
its really helping and helped my out. thanks a lot
Reply
crash 5 years ago
Completely awesome. My boss just asked me whip up a twitter feed for our social media group. Oh yeah, and it needs to be done in two hours. Found this and saved myself a HUGE headache! Thanks for this great tutorial.
Reply
JADE CLOWARD 5 years ago
Works like a charm. *Don't know why the Twitter JSON method does not work. Glad I found this. Thanks so much!!!!!!!!!!!!!!!!!
Reply
Karl 5 years ago
Is there a way to filter the feed using hashtag?
Reply
Matthew 5 years ago
Nice job, simple and functional
Reply
Sabir Abdul Gafoor 5 years ago
Fantastic, Really thank you for this scirpt. :)
Reply
tavax 5 years ago
Hi, great code.!

I have a question: is that possible to cache the callback function for don't having the 150 limit imposed by Twitter.

One person know it and share it for everybody?

ps: sorry I'm french and my english is bad :s
Reply
GR 5 years ago
I found one potential issue. Because of your .replace /ID/ line, if the tweets are in all caps, 'IDEA' will appear as '234976787782334EA'.
Reply
Rais 5 years ago
Nice tutorial.
But is there a way to remove the reply's?
Reply