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.

Get Latest Tweet

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.

Get latest tweet using WordPress HTTP API

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);

Cache latest tweet with WordPress transient

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!

🔥 HOT: Interested in boosting your WordPress SEO? My Slim SEO plugin is a super lighweight and automated plugin that handles most the hard work for you: meta tags, sitemap, redirection, schema & link building.

👉 Have a look and you will love it: wpslimseo.com

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2024 Deluxe Blog Tips. All rights reserved.

My products: Meta Box | Slim SEO