Displaying your latest Twitter entries

DISCLAIMER: The Twitter REST API v1 is no longer active.

Helping Carlos Eduardo from Webstandards blog, I’ve adjusted this coded posted at WPRecipes. We wanted to show the latest twitter entries in a WordPress blog.

You can show how many tweets you want with this updated code, instead of just the last one. Another improvement is the session-based cache to speed things up.

UPDATE: Due to charset compatibility I switched from regular expressions to json_decode function. It also makes the code smaller.

// Your Twitter username
$twitteruser = 'myuser';

// The number of tweets that have to be shown
$tweetsno = 10;

$tweets = NULL;
if (!empty($_SESSION['tweets'])) {
  $tweets = $_SESSION['tweets'];
} else {
  $feed = "http://search.twitter.com/search.json?"
      . "q=from:{$twitteruser}&rpp={$tweetsno}";
  $result = @json_decode(@file_get_contents($feed));
  if ($result) {
    $tweets = array();
    foreach ($result->results as $tweet) {
      $tweets[] = preg_replace('/(http:\/\/[a-z\d\-_\.\/\?&=%]+)/i',
          '<a href="$1" rel="external">$1</a>', $tweet->text);
    }
    $_SESSION['tweets'] = $tweets;
  }
}

You’ll have to change the values of  $twitteruser and $tweetsno to your Twitter username and the number of tweets you want.

To display the tweets, use the following just after the snippet above:

if (!empty($tweets)) {
  echo '<ul>';
  foreach ($tweets as $tweet) {
    echo '<li>' . $tweet . '</li>';
  }
  echo '</ul>';
}

 

Advertisements

One thought on “Displaying your latest Twitter entries

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s