How To: Easily Display Tweets with Twitter API 1.1 on WordPress

Here is how you can easily display tweets with twitter api 1.1 on wordpress blog. You might already know, that Twitter updated its API to version 1.1 in June 2013, and since then the previous 1.0 has been deprecated. Many blogs are still using the old twitter API for displaying tweets, that’s why they might see their twitter feed broken.

In that case, i strongly recommend them to consider updating their code since visitors don’t like a broken website. Now lets see how we should we go about doing that, step by step.

easily display tweets with twitter api 1.1 on wordpress How To: Easily Display Tweets with Twitter API 1.1 on Wordpress

Method 1: Manual Way (Getting your Hands Dirty)

Since Twitter has made a new rule that every request to the API must now be authenticated using the OAuth protocol, we cannot make a random request without using a Twitter App. This rule was made to help reduce the excessive use or abusive usage of its API. Of course, we will see less number of Twitter downtime now, but nevertheless it makes it quite difficult for users to implement this on their website, especially for webmasters.

Step 1: As explained above, in order to make a request to the Twitter API, we need a Twitter App. I have written a short and easy tutorial on how to quickly setup your own twitter app. Make sure you follow the instructions.

Read: How To: Create Your Own Twitter App in 5 Simple Steps

After setting up, you should have the following secret keys with you:

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

Copy them to Notepad or TextEdit (if you are on Mac), since you will need this later.

Step 2: We will be using Matt Harris’s tmhOAuth library for implementing the OAuth protocol. Download the ZIP file from GitHub. Now extract it. We are concerned with only the 2 files in it, which are:

  1. cacert.pem
  2. tmhOAuth.php.

Log in to your cpanel and go to your root directory. Create a new folder named “twitter” here and upload the two files i mentioned above, inside this folder.

Step 3: Paste the following code in your functions.php file:

//////////////////////////////////////////////////////////////////
//// 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 rel="nofollow" target="blank" title="$1" href="$1">$1</a>', $tweet_text);

            #Turn hashtags into links
             $tweet_text = preg_replace('/#([0-9a-zA-Z_-] )/', "<a rel=\"nofollow\" 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 rel=\"nofollow\" target='blank' title='$1' href=\"http://twitter.com/$1\">@$1</a>",  $tweet_text);

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

				$when  = '';

                 $twitter .= '<span class="twittime"><i class="icon-twitter"></i><a style="font-weight: normal; letter-spacing: normal; font-size: 11px;" rel="nofollow" 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;

///////////////////////////////////////////////////////////////////////////////
// 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 rel="nofollow" class="twitter-follow" href="https://twitter.com/<?php echo $twitter_username; ?>"><?php  _e("Join ",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');

You don’t have to edit anything here. Just copy paste it and you should be good to go.

If you read all the comments in the above code, you can easily understand what each block of code is doing. In the end, we are just creating a new twitter widget so that it will be easy for you to change the functionality of the widget such as the widget title, your twitter id, and the number of tweets you want to display from your user timeline.

Step 4: Go the Appearance > Widgets from your WordPress Dashboard. Now you should see a new twitter widget in the Available Widgets box. Just drag it and drop into your Footer area.

Here you can configure it. Copy paste the 4 secret keys we obtained from Step 1 and specify which twitter id you want to fetch your latest tweets from. All the other fields are self-explanatory.

easily display tweets with twitter api 1.1 on wordpress widget How To: Easily Display Tweets with Twitter API 1.1 on Wordpress

Finally, Save your changes, and voila your new twitter widget is ready. It should look something like above.

Credit: Dezzain.com

Method 2: Easy Way (Using a WordPress Plugin)

I shared the above method because i dislike using a plugin for everything. If you are a regular visitor of this site, you might know that we share a lot of wordpress without plugin tutorials with our users, so that they can increase the overall performance and speed of their site.

But if you want an easy way of integrating twitter with your site, then you might be better off with a plugin. There is no coding involved, just configure the plugin settings to your taste and you are done.

Here are the 2 best plugins i know of, for displaying your recent tweets using twitter’s new API 1.1:

You can install any one of them which you like.

Let us know if you found the above tutorial easy and useful. If you are looking for more twitter tutorials, be sure to subscribe to us!

Subscribe to our Weekly Newsletter

I take your privacy very seriously

Leave a Reply

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

Notify me of followup comments via e-mail.