Get Latest Tweet – The WordPress Way

Displaying latest tweet is a very common thing we do for WordPress theme. When I searched for a solution for this problem, I found many ways to do that. Most of these methods are using Twitter feed to and raw PHP to fetch the tweets. But I don’t like them, because:

  • They’re not using recent Twitter API
  • They’re not using any cache mechanism, like transient, which is supported by WordPress
  • And personally, I prefer using HTTP API to SimplePie which WordPress uses in its functions working with RSS. It might be a little faster as the HTTP class is much smaller than SimplePie

So, I’m going to get the latest tweet using HTTP API, transient to cache and recent Twitter API.

twitter Get Latest Tweet   The WordPress Way

Working with Twitter API

Twitter API is here, but it is too much for us to look at and might confuse us at first. What we need is just user timeline. You’ll see a lot of arguments, but in this post, we use only 3 arguments (feel free to add more):

  • screen_name: the twitter username, can’t omit this
  • count: we get only the latest tweets, right?
  • trim_user: this is optional, but I want to use it because it will cut off all user information, meaning the returned string is much shorter and thus our script will run faster

So, we’ll build the URL to Twitter like this:

$args = array(
    'screen_name' => $username,
    'count'       => 1,
    'trim_user'   => 1,
);
$url = 'https://api.twitter.com/1/statuses/user_timeline.json';
$url = add_query_arg( $args, $url );

The add_query_arg is very helpful in this situation. It helps us add query arguments faster than looping throught the array and add them like working with string.

264864230 6369ad4a3d Get Latest Tweet   The WordPress Way

Send request to Twitter using HTTP API

The code is really simple:

$request = wp_remote_get( $url );
if ( is_wp_error( $request ) )
    return;

$body = wp_remote_retrieve_body( $request );

It’s very simple. The HTTP API cares everything for us like cookie, connection timeout, which way is used to connect (cURL or not?), etc. We should always use it instead of writing our own cURL function.

If the request is sent successful (you can check it), we’ll get a json encoded string like this:

[{
    "created_at": "Fri Jul 13 02:00:43 +0000 2012",
    "id": 223597794173272065,
    "id_str": "223597794173272065",
    "text": "A new Guest post at DBT: How to create a successful Blog that gains popularity in quick time: http:\/\/t.co\/QJnwUo1W",
    "source": "\u003ca href=\"http:\/\/twitter.com\/tweetbutton\" rel=\"nofollow\"\u003eTweet Button\u003c\/a\u003e",
    "truncated": false,
    "in_reply_to_status_id": null,
    "in_reply_to_status_id_str": null,
    "in_reply_to_user_id": null,
    "in_reply_to_user_id_str": null,
    "in_reply_to_screen_name": null,
    "user": {
        "id": 14736998,
        "id_str": "14736998"
    },
    "geo": null,
    "coordinates": null,
    "place": null,
    "contributors": null,
    "retweet_count": 0,
    "favorited": false,
    "retweeted": false,
    "possibly_sensitive": false
}]

The latest tweet is stored in text attribute. So we’re going to decode it and get the latest tweet:

$body = json_decode( $body );
$tweet = $body[0]->text;

Note that the tweet is in plain text, you won’t see any links, hash or retweet links. To make those things linkable, use this code:

$tweet = utf8_decode( $tweet );
$tweet = preg_replace('@(https?://([-\w\.]+)+(d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>',  $tweet );
$tweet = preg_replace("#(^|[\n ])@([^ \"\t\n\r< ]*)#ise", "'\\1<a href=\"http://www.twitter.com/\\2\" >@\\2'", $tweet);  
$tweet = preg_replace("#(^|[\n ])\#([^ \"\t\n\r< ]*)#ise", "'\\1<a href=\"http://hashtags.org/search?query=\\2\" >#\\2'", $tweet);

4980648072 0edcd59228 Get Latest Tweet   The WordPress Way

Cache latest tweet

After retrieving tweet, we should cache it. We’ll use transient to do that, the cache time can be 1 hour (feel free to change if you want a longer or shorter cache time).

$key = "tweet-{$username}";
set_transient( $key, $tweet, 3600 );

And when the cache is available, we’ll just get its content without requesting to Twitter. We’ll need this code at the very beginning:

$key = "tweet-{$username}";
if ( false != ( $tweet = get_transient( $key ) ) )
    return $tweet;

So the full code is:

function yourprefix_latest_tweet( $username )
{
    $key = "tweet-{$username}";
    if ( false != ( $tweet = get_transient( $key ) ) )
        return $tweet;

    $args = array(
        'screen_name' => $username,
        'count'       => 1,
        'trim_user'   => 1,
    );
    $url = 'https://api.twitter.com/1/statuses/user_timeline.json';
    $url = add_query_arg( $args, $url );

    $request = wp_remote_get( $url );
    if ( is_wp_error( $request ) )
        return;

    $body = wp_remote_retrieve_body( $request );
    $body = json_decode( $body );
    $tweet = $body[0]->text;

    // Make links
    $tweet = utf8_decode( $tweet );
    $tweet = preg_replace('@(https?://([-\w\.]+)+(d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>',  $tweet );
    $tweet = preg_replace("#(^|[\n ])@([^ \"\t\n\r< ]*)#ise", "'\\1<a href=\"http://www.twitter.com/\\2\" >@\\2'", $tweet);  
    $tweet = preg_replace("#(^|[\n ])\#([^ \"\t\n\r< ]*)#ise", "'\\1<a href=\"http://hashtags.org/search?query=\\2\" >#\\2'", $tweet);

    set_transient( $key, $tweet, 3600 );

    return $tweet;
}

Using it in your WordPress theme is quite easily, simply insert:

echo yourprefix_latest_tweet( $username );

And don’t forget to style your latest tweet beautifully!

7 Comments

  1. Hey there,

    Did I use it correctly? I have added the full code into my function.php and I have added to my footer.php where I would like my latest tweet to be displayed. I have changed $username to $myusername

    It’s not working, so I’m assuming I forgot something?

    Reply
  2. How could I modify this code to display, say, the five most recent tweets?

    Reply
  3. Reply

Leave a Reply