How To Use New Twitter API V1.1 in WordPress

Today I’m going to show how to get the latest twitter status using the new Twitter REST API v1.1 and show it on a wordpress widget.

First we have to create a file named twitter_result.data inside our theme directory which we will use as a container for our twitter status so we won’t send a request to the twitter api everytime the page loads. It will act as a cache for our twitter status. We’ll just make a request every 10 minutes so as not to burn the request limit. Here is the detailed REST API v1.1 Limits.

Go to https://dev.twitter.com then create a new application and make sure you have created a new access token for your application.

Twitter OAuth settings

Take note of the Consumer key, Consumer secret, Access token and Access token secret because where gonna use it on the code below.

Copy the code below to your current template’s function.php file:

function buildBaseString($baseURI, $method, $params) {
    $r = array();
    ksort($params);
    foreach($params as $key=>$value){
        $r[] = "$key=" . rawurlencode($value);
    }
    return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}

function buildAuthHeader($oauth) {
    $r = 'Authorization: OAuth ';
    $values = array();
    foreach($oauth as $key=>$value)
        $values[] = "$key=\"" . rawurlencode($value) . "\"";
    $r .= implode(', ', $values);
    return $r;
}

function getTwitterStatusNew() {

  # check if cached twitter status not older than 10 mins is exists inside the twitter_result.data file
  if (file_exists(get_stylesheet_directory_uri().'/twitter_result.data')) {
    $data = unserialize(file_get_contents(get_stylesheet_directory_uri().'/twitter_result.data'));

    if ($data['timestamp'] > time() - 10 * 60) {
      $twitter_result = $data['twitter_result'];
    }
  }
  # if cache doesn't exist or is older than 10 mins
  if (!$twitter_result || empty($twitter_result)) {

    $url = "https://api.twitter.com/1.1/statuses/user_timeline.json";

    $oauth_access_token = "[ACCESS TOKEN]"; # Isert access token here
    $oauth_access_token_secret = "[ACCESS TOKEN SECRET]"; # Insert access token secret here
    $consumer_key = "[CONSUMER KEY]"; # Insert consumer key here
    $consumer_secret = "[CONSUMER KEY SECRET]"; # Insert consumer key secret here

    $oauth = array( 'oauth_consumer_key' => $consumer_key,
                    'oauth_nonce' => time(),
                    'oauth_signature_method' => 'HMAC-SHA1',
                    'oauth_token' => $oauth_access_token,
                    'oauth_timestamp' => time(),
                    'oauth_version' => '1.0');

    $base_info = buildBaseString($url, 'GET', $oauth);
    $composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
    $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
    $oauth['oauth_signature'] = $oauth_signature;

    // Make Requests
    $header = array(buildAuthHeader($oauth), 'Expect:');
    $options = array( CURLOPT_HTTPHEADER => $header,
                      CURLOPT_HEADER => false,
                      CURLOPT_URL => $url,
                      CURLOPT_RETURNTRANSFER => true,
                      CURLOPT_SSL_VERIFYPEER => false);

    $feed = curl_init();
    curl_setopt_array($feed, $options);
    $json = curl_exec($feed);
    curl_close($feed);

    if ($json != false) {

      $json_obj = json_decode($json);

      if (isset($json_obj->error) && $json_obj->error == 'Rate limit exceeded. Clients may not make more than 150 requests per hour.') {
        $text = "
Could not fetch Twitter Data. Follow @iamaronbarbosa.
"; } else { $text = "
"; $pattern = "/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/"; $json_text = $json_obj[0]->text; $json_url = $json_obj[0]->entities->urls[0]->url; $json_urls = $json_obj[0]->entities->urls; # Change URLs in the status into links if (preg_match_all($pattern, $json_text, $urlls)) { $text = $text.$json_text; foreach($urlls[0] as $v){ //current position of the searached url $curpos = strpos($text,' '.$v)+1; //delete the url $text = substr_replace($text,'', $curpos, strlen($v)); //insert the link $text = substr_replace($text,''.$v.'', $curpos ,0); } } $text .= "
"; } } else { $text = "
Could not fetch Twitter Data. Follow @iamaronbarbosa.
"; } $data = array ('twitter_result' => $text, 'timestamp' => time()); file_put_contents(get_stylesheet_directory_uri().'/twitter_result.data', serialize($data)); $twitter_result = $text; } return $twitter_result; } add_shortcode('get-latest-tweet','getTwitterStatusNew');

On line 34 to 37 add your own Consumer key, Consumer secret, Access token and Access token secret.

To use this you can create a new text widget then add the new shortcode:

Twitter status widget


[get-latest-tweet]

or you can add it programmaticaly on your theme file:

Example 1:


echo do_shortcode('[get-latest-tweet]');

Example 2:


if function_exists('getTwitterStatusNew') {
  echo getTwitterStatusNew();
}

Then we’re done. It will show something like this:
Twitter Widget

This entry was posted in Blog and tagged , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.