How To Display Twitter Feed on Website? Step By Step Guide!

display-twitter-feed-on-website-1
Before we start coding, let me ask you this: Do you really want to code this feature on your website? Or would you prefer to use a website plugin that does the trick instantly?

There is an easy way to customize & embed Twitter feed on your website. No coding required. How? Use the DSM Website Plugin! Learn how to use it from this Step by step tutorial.

Going back to coding…

Do you actively use Twitter for your brand or products? Does your client use it?

If you use it for your brands or products and you have your own website, it will be a great feature if you can display your twitter feed or posts on your website.

I know, you can embed your Twitter feed using the Twitter widget, but you cannot customize the look and feel.

It looks like the default Twitter interface.

Don’t get me wrong, it looks good! But sometimes, our design scheme or our clients have a different requirement, they want the Twitter feed to look different.

The good news is, our code for today is a way to do it!

Today’s post will cover the following content:

1.0 Source Code Overview
2.0 Final Output Demo
3.0 Obtain Access Tokens and Keys
4.0 Create The index.php File
5.0 Put Container Tags, Page Title and HTML
6.0 Specify Keys And Variable Values
7.0 Get OAuth Signature
8.0 Make The Authorization Request
9.0 Retrieve Twitter Feeds With User Information
10.0 Display Twitter User Information
11.0 Display Twitter User Status Count And Follower Count
12.0 Display Twitter Posts / Status Feed
13.0 Add Your Custom Styling
14.0 Control Background and Link Colors
15.0 Download The Source Code
16.0 Social Media Scripts – LEVEL 3 – PRO PACK
17.0 What’s Next?
18.0 Related Source Codes
19.0 Some Notes

Let’s get started!

1.0 Source Code Overview

Here’s an overview of what our code does:

1.1 It gets a Twitter users’s profile information and posts from a specified twitter account. We’ll try Taylor Swift’s twitter account in the demo.

1.2 Display these Twitter data to a webpage (assuming it is your WordPress or PHP website.)

1.3 Show some awesome UI powered by Bootstrap. If you’re not yet familiar with this awesome front-end framework, see our step by step Bootstrap tutorial here.

2.0 Final Output Demo

2.1 LEVEL 1 Source Code Output

We have to know where we are going, if we’re done with the code tutorial in this post, we will achieve this output:

display-twitter-feed-BASIC

2.2 LEVEL 2 Source Code Output

More improvements were provided after the step by step tutorial. If you need more features, you might need the LEVEL 2 version. It has the following output:

display-twitter-feed-pro-katy

display-twitter-feed-pro-ninjazhai

See the full list of features in section 15.0 below. It has all the details of these features.

3.0 Obtain Access Tokens and Keys

3.1 Go to Twitter Apps page.

3.2 Click the ‘Create New App’ button on the upper right corner.

3.3 Fill out the form with your information

3.4 Go back to the twitter apps page, you should see your new app now

3.5 Click your app and go to the “Keys and Access Tokens” tab

twitter-app-keys

There you will see the access tokens and keys you need:

  • Consumer Key (API Key)
  • Consumer Secret (API Secret)
  • Access Token
  • Access Token Secret

4.0 Create The index.php File

We will make index.php Bootstrap ready. For those not familiar with the CSS framework Bootstrap, please refer to our step by step tutorial here:

Step by Step Bootstrap Tutorial for Beginners

The index.php file will have the following code.

<!DOCTYPE html>
<html lang="en">
<head>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<title>Display Twitter Feed On Website - LEVEL 2 - Live Demo</title>

        <!-- Bootstrap CSS -->
	<link href="libs/js/bootstrap/dist/css/bootstrap.css" rel="stylesheet" media="screen">
</head>
<body>

<!-- PAGE CONTENT and PHP CODE WILL BE HERE -->

<!-- jQuery library -->
<script src="libs/js/jquery.js"></script>

<!-- bootstrap JavaScript -->
<script src="libs/js/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="libs/js/bootstrap/docs-assets/js/holder.js"></script>
 
<!-- HTML5 Shiv and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->

</body>
</html>

5.0 Put Container Tags, Page Title and HTML

We will have the following code inside the “body” tag of our code in section 4.0

<div class="container">

	<div class="col-lg-12">	
		<div class="page-header">
			<h1>Display Twitter Feed On Website - LEVEL 1 - Live Demo</h1>
		</div>
	</div>
	
	<div class="col-lg-4">
		<!-- TWITTER USER PROFILE INFORMATION WILL BE HERE -->
	</div> <!-- end <div class="col-lg-4"> -->

	<div class="col-lg-8">
		<!-- TWITTER USER FEED WILL BE HERE -->
	</div> <!-- end <div class="col-lg-8"> -->

</div> <!-- end <div class="container"> -->

6.0 Specify Keys And Variable Values

The following code will be inside the DIV tag with class=”col-lg-4″.

Access token and keys value were retrieved during our section 3.0 earlier.

<?php		
// keys from your app
$oauth_access_token = "change_to_your_oauth_access_token ";
$oauth_access_token_secret = "change_to_your_oauth_access_token_secret ";
$consumer_key = "change_to_your_consumer_key ";
$consumer_secret = "change_to_your_consumer_secret ";

// we are going to use "user_timeline"
$twitter_timeline = "user_timeline";

// specify number of tweets to be shown and twitter username
// for example, we want to show 20 of Taylor Swift's twitter posts
$request = array(
	'count' => '10',
	'screen_name' => 'taylorswift13'
);
?>

7.0 Get OAuth Signature

OAuth is an authentication protocol that allows users to approve application to act on their behalf without sharing their password. More about Twitter OAuth here.

Put the following code below our code on section 6.0

// put oauth values in one oauth array variable
$oauth = array(
	'oauth_consumer_key' => $consumer_key,
	'oauth_nonce' => time(),
	'oauth_signature_method' => 'HMAC-SHA1',
	'oauth_token' => $oauth_access_token,
	'oauth_timestamp' => time(),
	'oauth_version' => '1.0'
);

// combine request and oauth in one array
$oauth = array_merge($oauth, $request);

// make base string
$baseURI="https://api.twitter.com/1.1/statuses/$twitter_timeline.json";
$method="GET";
$params=$oauth;

$r = array();
ksort($params);
foreach($params as $key=>$value){
	$r[] = "$key=" . rawurlencode($value);
}
$base_info = $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);

// get oauth signature
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;

8.0 Make The Authorization Request

We can now make request to the Twitter API with the help of $oauth variable and cURL.

Put the follwing code below our code on section 7.0

// make request
// make auth header
$r = 'Authorization: OAuth ';

$values = array();
foreach($oauth as $key=>$value){
	$values[] = "$key=\"" . rawurlencode($value) . "\"";
}
$r .= implode(', ', $values);

// get auth header
$header = array($r, 'Expect:');

// set cURL options
$options = array(
	CURLOPT_HTTPHEADER => $header,
	CURLOPT_HEADER => false,
	CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
	CURLOPT_RETURNTRANSFER => true,
	CURLOPT_SSL_VERIFYPEER => true
);

9.0 Retrieve Twitter Feeds With User Information

Using the the following code, we can get the data in JSON format. Put it below our code on section 8.0

// retrieve the twitter feed
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);

// decode json format tweets
$tweets=json_decode($json, true);

10.0 Display Twitter User Information

The following code shows how we can display the specified Twitter user’s information. Put it below our code on section 9.0

// show user information
echo "<div class='overflow-hidden'>";

	// user data
	$profile_photo=str_replace("normal", "400x400", $tweets[0]['user']['profile_image_url_https']);
	$name=$tweets[0]['user']['name'];
	$screen_name=$tweets[0]['user']['screen_name'];
	
	// show profile photo
	echo "<img src='{$profile_photo}' class='img-thumbnail' />";
	
	// show other information about the user
	echo "<div class='text-align-center'>";
		echo "<div><h2>{$name}</h2></div>";
		echo "<div><a href='https://twitter.com/{$screen_name}' target='_blank'>@{$screen_name}</a></div>";
	echo "</div>";
	
	echo "<hr />";
echo "</div>";

11.0 Display Twitter User Status Count And Follower Count

Now we will put the following code inside the DIV tag with class=”col-lg-8″.

<?php
$statuses_count=$tweets[0]['user']['statuses_count'];
$followers_count=$tweets[0]['user']['followers_count'];

// show numbers
echo "<div class='overflow-hidden'>";

	// show number of tweets
	echo "<div class='float-left margin-right-2em text-align-center'>";
		echo "<div class='color-gray'>Tweets</div>";
		echo "<div class='badge font-size-20px'>" . number_format($statuses_count, 0, '.', ',') . "</div>";
	echo "</div>";
	
	// show number of followers
	echo "<div class='float-left margin-right-2em text-align-center'>";
		echo "<div class='color-gray'>Followers</div>";
		echo "<div class='badge font-size-20px'>" . number_format($followers_count, 0, '.', ',') . "</div>";
	echo "</div>";
	
echo "</div>";

echo "<hr />";
?>

12.0 Display Twitter Posts / Status Feed

Finally we can now display the user’s Twitter posts.

// show tweets
foreach($tweets as $tweet){
	
	// show a tweet
	echo "<div class='overflow-hidden'>";
		
		// show picture
		echo "<div class='tweet-image'>";
			echo "<img src='{$profile_photo}' class='img-thumbnail' />";
		echo "</div>";
		
		// show tweet content
		echo "<div class='tweet-text'>";
			
			// show name and screen name
			echo "<h4 class='margin-top-4px'>";
				echo "<a href='https://twitter.com/{$screen_name}'>{$name}</a> ";
				echo "<span class='color-gray'>@{$screen_name}</span>";
			echo "</h4>";
			
			// show tweet text
			echo "<div class='margin-zero'>";
			
				// get tweet text
				$tweet_text=$tweet['text'];
				
				// make links clickable
				$tweet_text=preg_replace('@(https?://([-\w\.]+)+(/([\w/_\.]*(\?\S+)?(#\S+)?)?)?)@', '<a href="$1" target="_blank">$1</a>', $tweet_text);
				
				// output
				echo $tweet_text;
			echo "</div>";
		echo "</div>";
		
	echo "</div>";
	echo "<hr />";
}

13.0 Add Your Custom Styling

The following CSS code is what I used to add a some style on our page. I put it inside the “head” tag, just below the Bootstrap CSS.

<!-- custom CSS -->
<style>
.overflow-hidden{
	overflow:hidden;
}

.left-margin-10px{
	margin:0 1em 0 0;
}

.margin-right-1em{
	margin-right:1em;
}

.margin-right-2em{
	margin-right:2em;
}

.text-align-center{
	text-align:center;
}

.margin-top-4px{
	margin-top:4px;
}

.color-gray{
	color:#999;
}

.tweet-image{
	float:left; width:15%;
	margin-right:1em;
}

.tweet-image img{
	width:100%;
}

.tweet-text{
	float:left; width:80%;
}

.margin-zero{
	margin:0;
}

.font-size-20px{
	font-size:20px;
}

.float-left{
	float:left;
}
</style>

14.0 Control Background and Link Colors

You can control or change the background or link colors by going to the design settings section of your twitter account.

Here’s how you can go to that page:

  1. Go to twitter.com.
  2. On the upper right corner of the page, click your picture.
  3. Click “Settings” in the dropdown.
  4. On the left side bar, click “Design”.

You should see the following page.

display-twitter-feed-pro-design-settings

“Theme Color” is the link color. Changes made here will reflect in your page using the LEVEL 2 source code.

15.0 Download The Source Code

15.1 Getting The Source Code

You can get the source code by following the whole, well detailed tutorial above. But isn’t it more convenient if you can just download the complete source code we used, and play around it?

There’s a small fee in getting the complete source code, it is small compared to the:

✔ Value or skill upgrade it can bring you, orYES
✔ Income you can get from your website project or business.YES
✔ Precious time you save.YES
✔ Expert advice you can get from me, just in case you have any questions with the code.YES

For a limited time, I will give you the source code for a low price. DOWNLOAD THE SOURCE CODE LEVEL you desire by clicking its the BUY button below.

15.1 Download the LEVEL 1 Source Code

FEATURESLEVEL 1
Show Twitter users’ profile pictureYES
Show Twitter users’ nameYES
Show Twitter users’ username with linkYES
Show number of tweetsYES
Show exact number of followersYES
Specify number of tweets to displayYES
Specify Twitter username where to get tweetsYES
Show profile pic in tweetsYES
Show profile name in tweetsYES
Show profile username in tweetsYES
Show original tweetsYES
Show retweetsYES
Links in tweets are clickableYES
Bootstrap enabledYES
Mobile friendlyYES
Download Now

15.2 Download LEVEL 2 Source Code

FEATURESLEVEL 2
All features of the LEVEL 1 versionYES
Show twitter profile descriptionYES
Show twitter user’s website with linkYES
Show number of followingYES
Show number of favoritesYES
Twitter profile mentions in tweets are clickableYES
Show when a tweet was tweeted with “Time ago” formatYES
Show profile banner imageYES
Apply background color set in design settingsYES
Apply link color set in design settingsYES
Download Now

Do you need more reasons to download it?

MORE REASONS TO GET IT
Buy only once, use on unlimited number of websites and Twitter accounts!YES
No different kind of licenses.YES
No many different pricing schemes.YES
No monthly or any recurring fees.YES
No need to rely on another website to render Twitter feed.YES
No need for codes from other websites.YES
You can learn more how to code, I love teaching and can give you free tips!YES
Familiarize yourself with the Twitter API.YES
Features are constantly improving, and you get it for free.YES
Completely customizable.YES

Thank you for supporting our projects here at codeofaninja.com!

15.3 Do You Want a Demo?

If you want a demo to see if this will work with your own Twitter account, please send me a message via email mike@codeofaninja.com, or via our official Facebook page!

Please provide your Twitter username on the message, thanks!

16.0 Social Media Scripts – LEVEL 3 – PRO PACK

Social Media Scripts - LEVEL 3 - PRO PACK
ITEMOriginal CostLEVEL 3 PRO PACK
Display Facebook EVENTS on Website$49.99YES
Display Facebook PHOTOS on Website$49.99YES
Display Facebook VIDEOS on Website$49.99YES
Display Facebook FEED on Website$49.99YES
Display Instagram FEED On Your Website$49.99YES
BONUS! The following script does not have LEVEL 3, only LEVEL 2. We will give them to you as bonus.
Display Twitter FEED on Website$29.99YES
Display Google+ FEED on Website$29.99YES
BUY TO DOWNLOAD LEVEL 3 PRO PACK NOW USING
Read more about this package. * You can use your debit or credit card with PayPal.

17.0 What’s Next?

Today we have learned how to show a Twitter Feed on your website.

Did you know that you can display Google+ Feed on your website as well?

Let us go to the next tutorial: How To Display Google+ Feed on Website?

18.0 Related Source Codes

Did you know that you can also display other social media data on your website? I’ve created tutorials on them too, see the following:

Social Media Script Tutorials
Display Facebook EVENTS on Website
Display Facebook PHOTOS on Website
Display Facebook VIDEOS on Website
Display Facebook TIMELINE on Website
Display Instagram FEED On Your Website
Display Twitter FEED on Website
Display Google+ FEED on Website

19.0 Some Notes

#1 Found An Issue?

If you found a problem with this code, we can solve it faster via Email or FB message, please send me a message via email mike@codeofaninja.com, or via our official Facebook page!

Please be more detailed about your issue. Best if you can provide an error message and your test or page URL. Thanks!

Please feel free to comment if you have any questions, suggestions, found something wrong or want to contribute to this code.

#2 Become a true Ninja!

  • 1. Subscribe to social media scripts tutorial news and updates.
  • 2. Be updated about what works and what does not work on social media APIs.
  • 3. Be notified for any related social media API updates.
100% Privacy. We will never spam you!

#3 Thank You!

Thanks for visiting our tutorial on how to display twitter feed on website using PHP!