How to use New Twitter API 1.1 to get User Timeline and Followers Count

new-twitter-timeline-and-count
Starting from 11th June 2013, Twitter will be retiring their API V1.0 and it will be fully replaced with the new API V1.1. The new Twitter API will be needing an Authenticated Privilege before they can work correctly. Twitter developer team said this can prevent excessive abusive usage of their API. However this move are not getting a good response by social developers around the community.

Why is that you might ask? according to one of the developer in discussion, it is unnecessary to require Authenticated Privilege to get a public user’s timeline. He think the Oauth should only be use in Authenticated access or Oauth logins. That means every Twitter users will need to create their their own apps to obtained the developer API which required for the new Twitter API Oauth. Today i am going to show you how to use the new Twitter API 1.1 to get user timeline and followers count.

1. Create An Application On Twitter

To start using the new API you need to be authenticated, which means Twitter needs to have certain information about your application and how it is going to be used so that it will provide you with access keys to use the API. To get the access keys you need to create an application on the Twitter Developer site.

Create-an-application-Twitter-Developers

First go to Twitter Developer site and login with your Twitter account. Proceed to My Application once logged-in. Enter an apps name, descriptions and url (this should be your site url) and leave callback url empty.

Once your application is created Twitter will generate your Oauth settings and your access tokens to your new application. You will need to use this data when connecting to the Twitter Oauth to query the Twitter API. There are 4 Authenticated code generated once everything completed. You should write and save the code in a notepad.

  • Consumer key
  • Consumer secret
  • Access token
  • Access token secret

2. Download Twitter Oauth PHP Class

Go to Github and download themattharris tmhOauth PHP. It is better to download the whole package but in my case, i only need 2 files from the package.

  • cacert.pem
  • tmhOAuth.php

create a new folder in your current theme root and named it ‘twitter’. Copy paste the above 2 files into the newly created folder.

3. Create functions for timeline and followers count

Copy paste the below code into your theme functions.php

[php]<?php
//////////////////////////////////////////////////////////////////
//// function to display tweets with api 1.1
//////////////////////////////////////////////////////////////////
if( !function_exists(‘wp_dez_get_twitter_timeline’) ):
function wp_dez_get_twitter_timeline (
$twitter_id,
$max_tweets,
$consumer_key,
$consumer_secret,
$user_token,
$user_secret
) {

$transient_name = ‘new_twitter_cache_’ . strtolower($twitter_id);
$twitter_cache = get_transient($transient_name);

require_once( get_template_directory() . ‘/twitter/tmhOAuth.php’ );

$tmhOAuth = new tmhOAuth(array(
‘consumer_key’ => $consumer_key, //Add your Twitter Consumer Key here
‘consumer_secret’ => $consumer_secret, //Add your Twitter Consumer Secret here
‘user_token’ => $user_token, //Add your Twitter User Token here
‘user_secret’ => $user_secret //Add your Twitter User Secret here
));

$twitter_data = $tmhOAuth->request(‘GET’, $tmhOAuth->url(‘1.1/statuses/user_timeline’), array(
‘screen_name’ => $twitter_id,
‘count’ => $max_tweets,
‘include_rts’ => true,
‘include_entities’ => true
));

//this will store in transient
$data = $tmhOAuth->response[‘response’];
$twitter_array = json_decode($data, true);

if( !$twitter_cache ) {
set_transient($transient_name, $twitter_array, 60 * 60); // 1 hour cache
}
//print_r( $twitter_cache );

/*== uncomment this and refresh to delete transient ==*/
//delete_transient($transient_name);
//delete_option($transient_name);

$twitter = ”;

if($twitter_cache):
foreach ( $twitter_cache as $tweet ) {
$pubDate = $tweet[‘created_at’];
$tweet_text = $tweet[‘text’];
$tweet_permalink = $tweet[‘id_str’];

$today = time();
$time = substr($pubDate, 11, 5);
$day = substr($pubDate, 0, 3);
$date = substr($pubDate, 7, 4);
$month = substr($pubDate, 4, 3);
$year = substr($pubDate, 25, 5);
$english_suffix = date(‘jS’, strtotime(preg_replace(‘/\s+/’, ‘ ‘, $pubDate)));
$full_month = date(‘F’, strtotime($pubDate));

#pre-defined tags
$default = $full_month . $date . $year;
$full_date = $day . $date . $month . $year;
$ddmmyy = $date . $month . $year;
$mmyy = $month . $year;
$mmddyy = $month . $date . $year;
$ddmm = $date . $month;

#Time difference
$timeDiff = dateDiff($today, $pubDate, 1);

# Turn URLs into links
$tweet_text = preg_replace(‘@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\./-]*(\?\S+)?)?)?)@’, ‘<a target="blank" title="$1" href="$1">$1</a>’, $tweet_text);

#Turn hashtags into links
$tweet_text = preg_replace(‘/#([0-9a-zA-Z_-]+)/’, "<a target=’blank’ title=’$1′ href=\"http://twitter.com/search?q=%23$1\">#$1</a>", $tweet_text);

#Turn @replies into links
$tweet_text = preg_replace("/@([0-9a-zA-Z_-]+)/", "<a target=’blank’ title=’$1′ href=\"http://twitter.com/$1\">@$1</a>", $tweet_text);

$twitter .= "<li><span class=’twittext’>" . $tweet_text . "</span>";

$when = ”;

$twitter .= ‘<span class="twittime"><i class="icon-twitter"></i><a target="_blank" class="time" href="https://twitter.com/’. $twitter_id . ‘/status/’. $tweet_permalink . ‘">’;

$twitter .= $timeDiff . "&nbsp;ago";

$twitter .= "</a></span></li>"; //end of List

//echo $twitter;

} //end of foreach

//store the tweets in options string
update_option($transient_name,$twitter);

endif;

echo stripcslashes( get_option($transient_name) );

}
endif;

//////////////////////////////////////////////////////////////////
//// function to get twitter follower count in api 1.1
//////////////////////////////////////////////////////////////////
if( !function_exists(‘wp_dez_get_twitter_count’) ):

function wp_dez_get_twitter_count(
$twitter_id,
$consumer_key,
$consumer_secret,
$user_token,
$user_secret
) {
// WordPress Transient API Caching

$transient_follower_name = ‘new_twitter_cache_follower_’ . strtolower($twitter_id);
$twitter_follower_cache = get_transient($transient_follower_name);

if( !$twitter_follower_cache ) {
require_once( get_template_directory() . ‘/twitter/tmhOAuth.php’ );

$tmhOAuth = new tmhOAuth(array(
‘consumer_key’ => $consumer_key, //Add your Twitter Consumer Key here
‘consumer_secret’ => $consumer_secret, //Add your Twitter Consumer Secret here
‘user_token’ => $user_token, //Add your Twitter User Token here
‘user_secret’ => $user_secret //Add your Twitter User Secret here
));

// Send the API request
$json = json_decode($tmhOAuth->request(
‘GET’,
$tmhOAuth->url(‘1.1/users/show.json’),
array(‘screen_name’ => $twitter_id )
));

// Extract the follower and tweet counts
$followerCount = json_decode($tmhOAuth->response[‘response’])->followers_count;
$tweetCount = json_decode($tmhOAuth->response[‘response’])->statuses_count;

$output = $followerCount;

if($output != ” || $output != ‘0’):
set_transient($transient_follower_name, $output, 60 * 60); //1 hour cache
update_option($transient_follower_name, $output);
endif;

}

/*== uncomment this and refresh to delete transient ==*/
//delete_transient($transient_follower_name);
//delete_option($transient_follower_name);

return number_format( get_option($transient_follower_name) );

}

endif;

//////////////////////////////////////////////////////////////////
//// function for counting date
//////////////////////////////////////////////////////////////////
if( !function_exists(‘dateDiff’) ):
function dateDiff($time1, $time2, $precision = 6) {
if (!is_int($time1)) {
$time1 = strtotime($time1);
}
if (!is_int($time2)) {
$time2 = strtotime($time2);
}
if ($time1 > $time2) {
$ttime = $time1;
$time1 = $time2;
$time2 = $ttime;
}
$intervals = array(
‘year’,
‘month’,
‘day’,
‘hour’,
‘minute’,
‘second’
);
$diffs = array();
foreach ($intervals as $interval) {
$diffs[$interval] = 0;
$ttime = strtotime("+1 " . $interval, $time1);
while ($time2 >= $ttime) {
$time1 = $ttime;
$diffs[$interval]++;
$ttime = strtotime("+1 " . $interval, $time1);
}
}
$count = 0;
$times = array();
foreach ($diffs as $interval => $value) {
if ($count >= $precision) {
break;
}
if ($value > 0) {
if ($value != 1) {
$interval .= "s";
}
$times[] = $value . " " . $interval;
$count++;
}
}
return implode(", ", $times);
}
endif;
?>[/php]

4. How do i use the functions

– to get a list of latest tweets from user timeline, just place this code anywhere in template.

[php]<?php echo wp_dez_get_twitter_timeline (‘user screen_name’,’tweet count’,’consumer_key’,’consumer_secret’,’user_token’,’user_secret’ ); ?>[/php]

the correct result should be like this

[php]<?php echo wp_dez_get_twitter_timeline (‘Dezzains’,’10’,’xxxxCODExxxx’,’xxxxCODExxxx’,’xxxxCODExxxx’,’xxxxCODExxxx’ ); ?>[/php]

– to get follower count from user, just place this code anywhere in template.

[php]<?php echo wp_dez_get_twitter_count (‘user screen_name’,’consumer_key’,’consumer_secret’,’user_token’,’user_secret’ ); ?>[/php]

the correct result should be like this

[php]<?php echo wp_dez_get_twitter_count (‘Dezzains’,’xxxxCODExxxx’,’xxxxCODExxxx’,’xxxxCODExxxx’,’xxxxCODExxxx’ ); ?>
[/php]

ok, that’s quite easy right? but how about creating a multi-instance widgets for the Twitter?

5. Creating a Widget for Twitter

If you prefer to use widget for the Twitter, just copy paste below extra code to your functions.php

[php]
///////////////////////////////////////////////////////////////////////////////
// multi instance twitter widget
///////////////////////////////////////////////////////////////////////////////
class My_THEME_Twitter_Widget extends WP_Widget {
function My_THEME_Twitter_Widget() {
//Constructor
parent::WP_Widget(false, $name = TEMPLATE_DOMAIN . ‘ | Twitter’, array(
‘description’ => __(‘Display your latest twitter.’, TEMPLATE_DOMAIN)
));
}

function widget($args, $instance) {
// outputs the content of the widget
extract($args); // Make before_widget, etc available.

$twitter_consumer_key = isset($instance[‘twitter_consumer_key’]) ? $instance[‘twitter_consumer_key’] : "";
$twitter_consumer_secret = isset($instance[‘twitter_consumer_secret’]) ? $instance[‘twitter_consumer_secret’] : "";
$twitter_user_token = isset($instance[‘twitter_user_token’]) ? $instance[‘twitter_user_token’] : "";
$twitter_user_secret = isset($instance[‘twitter_user_secret’]) ? $instance[‘twitter_user_secret’] : "";
$twitter_username = isset($instance[‘twitter_username’]) ? $instance[‘twitter_username’] : "";
$twitter_count = isset($instance[‘twitter_count’]) ? $instance[‘twitter_count’] : "";

$twitter_title = empty($instance[‘title’]) ? __(‘Twitter’, TEMPLATE_DOMAIN) : apply_filters(‘widget_title’, $instance[‘title’]);
$unique_id = $args[‘widget_id’];

echo $before_widget;
echo $before_title . $twitter_title . $after_title; ?>
<ul class="twitterbox" id="twitter_update_list_<?php echo $unique_id; ?>">

<?php echo wp_dez_get_twitter_timeline (
$twitter_username,
$twitter_count,
$twitter_consumer_key,
$twitter_consumer_secret,
$twitter_user_token,
$twitter_user_secret ); ?>

<li class="followme"><a style="font-weight: normal; letter-spacing: normal; font-size: 11px;" href="https://twitter.com/<?php echo $twitter_username; ?>"><?php _e("Joined ",TEMPLATE_DOMAIN); ?>
<?php echo wp_dez_get_twitter_count (
$twitter_username,
$twitter_consumer_key,
$twitter_consumer_secret,
$twitter_user_token,
$twitter_user_secret );
?> <?php _e("Followers @",TEMPLATE_DOMAIN); ?><?php echo $twitter_username; ?></a></li>

</ul>
<?php echo $after_widget;
}

function update($new_instance, $old_instance) {
//update and save the widget
return $new_instance;
}

function form($instance) {
// Get the options into variables, escaping html characters on the way
$twitter_consumer_key = isset($instance[‘twitter_consumer_key’]) ? $instance[‘twitter_consumer_key’] : "";
$twitter_consumer_secret = isset($instance[‘twitter_consumer_secret’]) ? $instance[‘twitter_consumer_secret’] : "";
$twitter_user_token = isset($instance[‘twitter_user_token’]) ? $instance[‘twitter_user_token’] : "";
$twitter_user_secret = isset($instance[‘twitter_user_secret’]) ? $instance[‘twitter_user_secret’] : "";
$twitter_username = isset($instance[‘twitter_username’]) ? $instance[‘twitter_username’] : "";
$twitter_count = isset($instance[‘twitter_count’]) ? $instance[‘twitter_count’] : "";
$twitter_title = empty($instance[‘title’]) ? __(‘Twitter’, TEMPLATE_DOMAIN) : apply_filters(‘widget_title’, $instance[‘title’]);
?>

<p>
<label for="<?php echo $this->get_field_id(‘title’); ?>"><?php _e("Twitter Title:",TEMPLATE_DOMAIN); ?></label>
<input class="widefat" type="text" id="<?php echo $this->get_field_id(‘title’); ?>" name="<?php echo $this->get_field_name(‘title’); ?>" value="<?php echo $twitter_title; ?>" />
</p>

<p><label for="<?php echo $this->get_field_id(‘twitter_consumer_key’); ?>">
<?php echo __(‘Twitter Consumer Key:’, TEMPLATE_DOMAIN)?></label>
<input class="widefat" type="text" id="<?php echo $this->get_field_id(‘twitter_consumer_key’); ?>" name="<?php echo $this->get_field_name(‘twitter_consumer_key’); ?>" value="<?php echo $twitter_consumer_key; ?>" />
</p>

<p><label for="<?php echo $this->get_field_id(‘twitter_consumer_secret’); ?>">
<?php echo __(‘Twitter Consumer Secret:’, TEMPLATE_DOMAIN)?></label>
<input class="widefat" type="text" id="<?php echo $this->get_field_id(‘twitter_consumer_secret’); ?>" name="<?php echo $this->get_field_name(‘twitter_consumer_secret’); ?>" value="<?php echo $twitter_consumer_secret; ?>" />
</p>

<p><label for="<?php echo $this->get_field_id(‘twitter_user_token’); ?>">
<?php echo __(‘Twitter User Token:’, TEMPLATE_DOMAIN)?></label>
<input class="widefat" type="text" id="<?php echo $this->get_field_id(‘twitter_user_token’); ?>" name="<?php echo $this->get_field_name(‘twitter_user_token’); ?>" value="<?php echo $twitter_user_token; ?>" />
</p>

<p><label for="<?php echo $this->get_field_id(‘twitter_user_secret’); ?>">
<?php echo __(‘Twitter User Secret:’, TEMPLATE_DOMAIN)?></label>
<input class="widefat" type="text" id="<?php echo $this->get_field_id(‘twitter_user_secret’); ?>" name="<?php echo $this->get_field_name(‘twitter_user_secret’); ?>" value="<?php echo $twitter_user_secret; ?>" />
</p>

<p><label for="<?php echo $this->get_field_id(‘twitter_username’); ?>">
<?php echo __(‘Twitter ID:’, TEMPLATE_DOMAIN)?></label>
<input class="widefat" type="text" id="<?php echo $this->get_field_id(‘twitter_username’); ?>" name="<?php echo $this->get_field_name(‘twitter_username’); ?>" value="<?php echo $twitter_username; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id(‘twitter_count’); ?>"><?php echo __(‘Number Of Tweets:’, TEMPLATE_DOMAIN)?></label>
<input class="widefat" type="text" id="<?php echo $this->get_field_id(‘twitter_count’); ?>" name="<?php echo $this->get_field_name(‘twitter_count’); ?>" value="<?php echo $twitter_count; ?>" />
</p>

<?php
}
}
register_widget(‘My_THEME_Twitter_Widget’);
[/php]

Final Summary

If everything went well, you should be able to use both manual insert code or the multi-instance twitter widget with no problems. As always if you do not want to get your hand dirty, just download the source zip below.

[notice type=”downloads”]Download Twitter Feed and Count PHP Code here
file size:140kb    file type: zip[/notice]

image credit via deviantart

Scroll to Top