Previously, we learned how to display an Instagram feed on your website using PHP.
Today, this tutorial will help you learn how to display a Twitter feed on your website using PHP. Twitter is a powerful tool for businesses and individuals looking to promote their brands or products.
If you’re running a website for your brand, it makes sense to incorporate your Twitter feed into your website. This allows your followers to stay updated with your latest tweets without ever having to leave your site.
However, the standard Twitter widget may not always be the best fit for your website’s design. That’s why we’ll show you how to customize the look and feel of your Twitter feed to match your website’s design scheme.
You’ll learn how to retrieve tweets, format them, and display them on your website using PHP. So, whether you’re a developer or just looking to add this feature to your website, this tutorial is for you.
Before we start coding, you might be someone not really interested in coding. Or, you just want a quick solution to adding a Twitter feed to your website.
If that’s the case, you need to use a “no code” approach. One way of doing it is to use a website plugin called SociableKIT. It is a free website plugin that allows you to embed your Twitter feed on your website. No coding is required.
Let’s go back to coding below.
Here’s an overview of what our code does:
We have to know where we are going. If we’re done with the code tutorial in this post, we will achieve this output:
Go to Twitter Apps page.
Click the ‘Add App’ button.
Fill out the form with your information
Go back to the twitter apps page, you should see your new app now
Click your app and go to the “Keys and Access Tokens” tab
There you will see the Bearer Token you need:
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>
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"> -->
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 $tweets = []; $bio = []; // max tweet results when retrieving tweets $max_results = "5"; // get profile username $username=isset($_GET['username']) ? $_GET['username'] : "SociableKIT_hq"; // data to be retrieve when retrieving profile bio $bio_fields = 'user.fields=created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,url,username,verified,withheld&expansions=pinned_tweet_id'; // data to be retrieve when retrieving tweets $tweet_fields = 'tweet.fields=attachments,author_id,context_annotations,conversation_id,created_at,edit_controls,edit_history_tweet_ids,entities,geo,id,in_reply_to_user_id,lang,note_tweet,possibly_sensitive,public_metrics,referenced_tweets,reply_settings,source,text,withheld&expansions=attachments.media_keys,referenced_tweets.id&media.fields=duration_ms,height,media_key,preview_image_url,public_metrics,type,url,width,alt_text'; // bio data url $bioUrl = "https://api.twitter.com/2/users/by/username/".$username."?".$bio_fields; // tweets url $tweetsUrl = ""; // bearer token from your app $bearerToken = "YOUR_BEARER_TOKEN"; ?>
We can now make request to the Twitter API with the bearer token from your app using cURL.
The code below will allow us to retrieve the bio information.
Put the follwing code below our code on section 5.0
// request header to be use, the bearer token will be use here. $headers = array( 'Authorization: Bearer ' . $bearerToken ); $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_URL, $bioUrl); $response = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // check if request is successful if ($httpcode >= 200 && $httpcode < 300) { $original_response = json_decode($response, true); // store the bio data retrieve from API to the $bio variable $bio = $original_response['data']; $profile_id = isset($bio['id']) ? $bio['id'] : ""; $tweetsUrl = 'https://api.twitter.com/2/users/' . $profile_id . '/tweets?' . $tweet_fields . '&max_results=' . $max_results; } else { echo 'Error: HTTP ' . $httpcode; } );
We can now make request to the Twitter API with the bearer token from your app using cURL.
The code below will allow us to retrieve the tweets.
Put the follwing code below our code on section 6.0
$ch = curl_init(); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_URL, $tweetsUrl); $response = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($httpcode >= 200 && $httpcode < 300) { $original_response = json_decode($response, true); // store the tweets data retrieve from API to the $tweets variable $tweets = $original_response['data']; } else { echo 'Error: HTTP ' . $httpcode; } curl_close($ch);
The following code shows how we can display the specified Twitter user’s information. Put it below our code on section 9.0
echo "<div class='col-lg-4' style='margin-top:-13.5em;'>"; // show user information echo "<div class='overflow-hidden bio-container'>"; // user data $profile_photo = isset($bio['profile_image_url']) ? $bio['profile_image_url'] : ""; $name = isset($bio['name']) ? $bio['name'] : ""; $screen_name = isset($bio['username']) ? $bio['username'] : ""; $location = ""; $description = isset($bio['description']) ? $bio['description'] : ""; $url = isset($bio['url']) ? $bio['url'] : ""; $display_url = isset($bio['url']) ? $bio['url'] : ""; $verified = isset($bio['verified']) ? $bio['verified'] : ""; // 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>{$location}</div>"; echo "<div>{$description}</div>"; echo "<div><a href='{$url}' target='_blank'>{$display_url}</a></div>"; echo "</div>"; echo "<hr />"; echo "</div>";
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 $date = new DateTime($tweet['created_at']); $created_at = $utils->getTimeAgo($date->format('F j, Y')); $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); // make users clickable $tweet_text = preg_replace('/@(\w+)/', '<a href="https://twitter.com/$1" target="_blank">@$1</a>', $tweet_text); // make hashtags clickable $tweet_text=preg_replace('/\#([a-z0-9]+)/i', '<a href="https://twitter.com/search?q=%23$1" target="_blank">#$1</a>', $tweet_text); // output echo $tweet_text; echo "<div class='color-gray'>{$created_at}</div>"; echo "</div>"; echo "</div>"; echo "</div>"; echo "<hr />"; }
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>
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:
You should see the following page.
“Theme Color” is the link color.
You can choose whether to download our source code or use the SociableKIT Twitter feed widget.
FEATURES | Code | SociableKIT |
---|---|---|
Show Twitter users’ profile picture | ✔ | ✔ |
Show Twitter users’ name | ✔ | ✔ |
Show Twitter users’ usernames with link | ✔ | ✔ |
Show the number of tweets | ✔ | ✔ |
Show exact number of followers | ✔ | ✔ |
Specify number of tweets to display | ✔ | ✔ |
Specify Twitter username where to get tweets | ✔ | ✔ |
Show profile pic in tweets | ✔ | ✔ |
Show profile name in tweets | ✔ | ✔ |
Show profile username in tweets | ✔ | ✔ |
Show original tweets | ✔ | ✔ |
Show retweets | ✔ | ✔ |
Links in tweets are clickable | ✔ | ✔ |
Responsive, mobile-friendly layout | ✔ | ✔ |
No coding required | – | ✔ |
Works with any website builders like WordPress, Squarespace, or Wix | – | ✔ |
Customize colors, font, and more | – | ✔ |
Priority chat and email support | – | ✔ |
Lifetime support and system updates | – | ✔ |
No need to worry about Twitter API updates | – | ✔ |
Use the buttons below. ↓ | Code | SociableKIT |
Congratulations! You completed our series! For now, that is all for our social media API tutorial series.
You may want to explore a different tutorial series. Please select from our web development tutorials.
[adinserter block=”3″]