Embed a Twitter feed on your website

Mar 12, 2020 | Blog, Web Design Blog

web design blog embed twitter

A few years ago Twitter closed it’s API off meaning that if you’re looking to embed a Twitter feed on your site then you have to use their Oauth authentication.

Here’s a nice function that allows you to embed a list of your latest tweets on your site, just to keep things simple I won’t add any CSS.

1) The first step is to create a Twitter app, i could give you a little guide on this but it’s already been done nicely here

2) You’ll then need to copy and paste the Consumer Key, Consumer Secret, Access Token and Access Token Secret into the defined Constant variables below.

3) The third thing that we’ll need is the Twitter Oauth code from Abraham Williams

4) You’ll then need to include the path to the above Twitter Oauth code in the defined constant variables below.

5) The main function creates a session variable to store your tweets. This is to prevent the Twitter API being called each time a page of your site is loaded.

6) We’re also using a function to make links out of hashtags and @ content, this came from Jacob Tomlinson

7) To display the feed on your page you’ll add the following with your Twitter username (without an @) and the number of tweets you’d like to show.



//define your constant variables


//this extracts the hashtags and @ references and makes them into links

function linkify_tweet($tweet) {
$tweet = preg_replace("/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/", "<a target=\"_blank\" href=\"$1\">$1</a>", $tweet);
$tweet = preg_replace("/#([A-Za-z0-9\/\.]*)/", "<a target=\"_new\" href=\"http://twitter.com/search?q=$1\">#$1</a>", $tweet);
$tweet = preg_replace("/@([A-Za-z0-9\/\.]*)/", "<a href=\"http://www.twitter.com/$1\">@$1</a>", $tweet);
return $tweet;

//the main function that gets your latest tweets and displays them as an unordered list

function doTwitter($twitteruser,$number_tweets){ 
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$number_tweets."&include_entities=true");
$tweets =json_encode($tweets);
$twts = json_decode($tweets,true);
$out ="
<ul class='twitter-list'>";
foreach($twts as $t => $twt){
$out.="<li class='tweet'>".linkify_tweet($twt['text'])."</li>"; }
$out .="</ul>";
$_SESSION['my_twitter'] = $out;
return $_SESSION['my_twitter'];

//this to display the function

echo doTwitter("your_twitter_username","number_of_tweets_you_want_to_show");



Our web design & marketing blog

We live and breathe in the digital world which may be a bit geeky but we're passionate about our work and love sharing our knowledge with you.

Need our Assistance?

We’d love to work with you on your new project get in touch with us today