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
//////////////////////////////////////////////////////////////////
//// 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;
?>

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 echo wp_dez_get_twitter_timeline ('user screen_name','tweet count','consumer_key','consumer_secret','user_token','user_secret' ); ?>

the correct result should be like this

<?php echo wp_dez_get_twitter_timeline ('Dezzains','10','xxxxCODExxxx','xxxxCODExxxx','xxxxCODExxxx','xxxxCODExxxx' ); ?>

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

<?php echo wp_dez_get_twitter_count ('user screen_name','consumer_key','consumer_secret','user_token','user_secret' ); ?>

the correct result should be like this

<?php echo wp_dez_get_twitter_count ('Dezzains','xxxxCODExxxx','xxxxCODExxxx','xxxxCODExxxx','xxxxCODExxxx' ); ?>

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

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

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.

Download Twitter Feed and Count PHP Code here
file size:140kb    file type: zip

image credit via deviantart

How to use New Twitter API to get User Timeline and Followers Counthttp://cdn.dezzain.com/1/2013/06/new-twitter-timeline-and-count.jpghttp://cdn.dezzain.com/1/2013/06/new-twitter-timeline-and-count-300x300.jpg Richie KS WordPress Tutorialsapi 1.1,Editor Picks,twitter,wordpress coding,wp plugin
Learn how to use the new twitter API to get user timeline and followers count in 5 easy step. You can also create a multi-instance widgets for the new twitter API

72 Comments Already

  1. Dear,
    i have used your codes to get the tweets and its working fine….but the issue for every refresh i have to comment and uncomment that 2 lines..delete_transient($transient_follower_name);
    delete_option($transient_follower_name);

    otherwise no tweets will show there…..please let me know how i can fix that u can test that online from this link
    janxcode.com/expobiz/

    regards,
    Farooq

    Public CommentUserDear, i have used your codes to get the tweets and its working fine....but the issue for every refresh i have to comment and uncomment that 2 lines..delete_transient($transient_follower_name); delete_option($transient_follower_name); otherwise no tweets will show there.....please let me know how i can fix that u can test that online from this link janxcode.com/expobiz/ regards, Farooq
    • if you’re using wp, try the social jet wp plugin instead.

      Member of Dezzain.comAdministratorif you're using wp, try the <a href="http://www.dezzain.com/wordpress-plugins/social-jet/" rel="nofollow">social jet wp plugin</a> instead.
      • Dear,
        thank for your reply, the thing is that o am developing WordPress theme and would like to minimize the usage of any additional plugins… so for that i would like to have it as a part pf the theme.

        Is there a way to fix this widget to work on WordPress theme

        Public CommentUserDear, thank for your reply, the thing is that o am developing WordPress theme and would like to minimize the usage of any additional plugins... so for that i would like to have it as a part pf the theme. Is there a way to fix this widget to work on WordPress theme
        • see my latest post on twitter feed with js only.

          Member of Dezzain.comAdministratorsee my latest post on twitter feed with js only.
  2. Great article! Just a quick note – you could use WP’s built in function for date/time human_time_diff(), it would reduce the code. For example:
    human_time_diff( strtotime( $tweet['created_at'] ) ) .’ ago';

    No need to write your own, function is part of the core since 1.5!

    Public CommentUserGreat article! Just a quick note - you could use WP's built in function for date/time human_time_diff(), it would reduce the code. For example: human_time_diff( strtotime( $tweet['created_at'] ) ) .' ago'; No need to write your own, function is part of the core since 1.5!
  3. You are really Great.
    Working perfect.

    thanks,
    Amarnath.TSR

    Public CommentUserYou are really Great. Working perfect. thanks, Amarnath.TSR
  4. Can’t get this working at all!

    Public CommentUserCan't get this working at all!
  5. Hi ! This piece of code is working flawlessly but i want to get the date format in French, how can i do that ?
    Like, instead of 1 day ago, i want il y a un jour.

    Thanks

    Public CommentUserHi ! This piece of code is working flawlessly but i want to get the date format in French, how can i do that ? Like, instead of 1 day ago, i want il y a un jour. Thanks
  6. Hello, great post! I was able to get it to work perfectly. I’m just wondering if there is a way to add a function to display the total tweet count for an account?
    I see in your code there is a line 149 of your code you are extracting the statuses_count in the $tweetCount variable…I tried creating a new function using the $tweetCount as the $output variable but it is still just giving me the followers count.

    Thanks for any help

    Public CommentUserHello, great post! I was able to get it to work perfectly. I'm just wondering if there is a way to add a function to display the total tweet count for an account? I see in your code there is a line 149 of your code you are extracting the statuses_count in the $tweetCount variable...I tried creating a new function using the $tweetCount as the $output variable but it is still just giving me the followers count. Thanks for any help
  7. I do not even know the way I stopped up here,
    but I assumed this put up was once good. I don’t know who you’re but
    definitely you are going to a well-known blogger when you
    aren’t already. Cheers!

    Public CommentUserI do not even know the way I stopped up here, but I assumed this put up was once good. I don't know who you're but definitely you are going to a well-known blogger when you aren't already. Cheers!
  8. i need code for corephp for getting twitter count

    Public CommentUseri need code for corephp for getting twitter count
  9. i got this error
    Call to undefined function get_transient();

    Public CommentUseri got this error Call to undefined function get_transient();
  10. hi
    i got this error can u please tell solution.
    Fatal error: Class ‘WP_Widget’ not found in C:\vhosts\iwilltek.com\httpdocs\twitter\add-to-functions.php.php on line 228

    Public CommentUserhi i got this error can u please tell solution. Fatal error: Class 'WP_Widget' not found in C:\vhosts\iwilltek.com\httpdocs\twitter\add-to-functions.php.php on line 228
    • this php code is for site using wordpress only.

      Member of Dezzain.comAdministratorthis php code is for site using wordpress only.
      • can u give code for corephp

        Public CommentUsercan u give code for corephp
        • this is originaly made for normal php site, check this link

          Member of Dezzain.comAdministratorthis is originaly made for normal php site, check this <a href="https://github.com/themattharris/tmhOAuth" rel="nofollow">link</a>
  11. works great, but can anybody tell me how to change the intervals(year, month, day, hour etc.) into another language in the function.

    Public CommentUserworks great, but can anybody tell me how to change the intervals(year, month, day, hour etc.) into another language in the function.
  12. Thank you a bunch for sharing this with all people you actually realize what you are speaking
    about! Bookmarked. Kindly additionally talk over with my site =).

    We could have a hyperlink exchange agreement between us

    Public CommentUserThank you a bunch for sharing this with all people you actually realize what you are speaking about! Bookmarked. Kindly additionally talk over with my site =). We could have a hyperlink exchange agreement between us
  13. Thanks!! It was the only way that worked for me for a moment, but now i’m having some issues.

    The code was doing right, but them I’d noticed that it wasn’t updating with new posts, so i’ve tried to do all this steps that you’d said above, but right after uncomment the line delete_transient() and comment again the twitter box disappeared and it didn’t appeared anymore.

    I’ve tried everything. I’ve tried creating another application on twitter and installing all stuff again, but it’s not working, the box just dissapeared. :(

    Sorry for my english, but i don’t know what to do. Can somebody help me please? :(

    Public CommentUserThanks!! It was the only way that worked for me for a moment, but now i'm having some issues. The code was doing right, but them I'd noticed that it wasn't updating with new posts, so i've tried to do all this steps that you'd said above, but right after uncomment the line delete_transient() and comment again the twitter box disappeared and it didn't appeared anymore. I've tried everything. I've tried creating another application on twitter and installing all stuff again, but it's not working, the box just dissapeared. :( Sorry for my english, but i don't know what to do. Can somebody help me please? :(
    • do you have wp-cache or any cache plugin installed? this is known issues
      if yes, new twitter feed will only showed after 1 hour from your tweets. try clear your cache.

      Member of Dezzain.comAdministratordo you have wp-cache or any cache plugin installed? this is known issues if yes, new twitter feed will only showed after 1 hour from your tweets. try clear your cache.
  14. Thanks for this! It works perfectly!!!!

    Public CommentUserThanks for this! It works perfectly!!!!
1 2

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>