Blog

Thoughts, articles and tutorials about web and design.

twitter-bird-white-on-blue

How To Add A Twitter Feed To Your Website

It is very simple to add a Twitter feed to your own website without using Twitter’s default UI widget, which frankly looks quite ugly. If you want full customization ability, keep on reading and I’ll show you what to do using a bit of PHP.

To pull the Tweets from the Twitter API I have created a PHP Function with a few parameters in order to give it some extra flexibility. You are for example able to change the username, amount of tweets to show and whether to show or hide the username that appears first in the tweet when it is pulled from the API.

The Code

Here is the function in question. If you are using WordPress you should consider turning this into its own plugin so that it is available regardless of the theme, however if you really just need it quickly, drop this into your functions.php file.

function latest_tweets($username, $amount = 2, $removeUserID = true){

    $doc = new DOMDocument();
    $feed = "http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=$username";

    $doc->load($feed); 

      $outer = '<ul id="tweets">';

      $i = 1;

      foreach ($doc->getElementsByTagName('item') as $node) {

        $tweet = $node->getElementsByTagName('title')->item(0)->nodeValue;
        if($removeUserID)
        	$tweet = substr($tweet, stripos($tweet, ':') + 1);

        $tweet = preg_replace('@(https?://([-w.]+)+(:d+)?(/([w/_.]*(?S+)?)?)?)@',
              '<a href="$1">$1</a>', $tweet);

        $tweet = preg_replace('/@([0-9a-zA-Z]+)/',
              '<a href="http://twitter.com/$1">@$1</a>',
              $tweet);

        $outer .= '<li class"tweet">'. $tweet . '</li>';

        if($i++ >= $amount) break;

      }

	$outer .= "</ul>";

    echo $outer;
}

Showing the Tweets

Having created the function, showing the tweets is very easy. The function that you just created can be called as follows:

<?php latest_tweets($username, $amount, $removeUserID); ?>

$username should be your Twitter username.
$amount should be replaced with a number.
$removeUserID can be set to true if you want to remove it or false if you don’t.

To have the function show the three latest tweets from @ErikBernskiold without showing my username for every tweet, this is how the function would look:

<?php latest_tweets('ErikBernskiold', 5, true); ?>

Summing it up

This short and simple function is flexible enough to allow you to implement this wherever you need and in any content management system that you wish to use it in.

What ways are you using to show Twitter on your website? Sound off in the comments!