Skip to main content Jump to list of all articles

WordPress – Display your Cached Tweets using PHP and OAuth

Primarily the focus of this tutorial is to display your cached tweets using PHP and OAuth on your WordPress website. We will be accessing the secure Twitter 1.1 API with PHP by parsing and caching the JSON file using the WordPress API. It may seem a lot of code just to display your latest tweets on your website but the benefits are that you can style it to the taste of your theme with a little CSS and caching the JSON file will not add extra load on the Twitter API.

New Update. I have packaged all of the features and more into a WP plugin. Please remember to remove any of the code used from this post before installing the plugin. Check out WOW-Twitter.

Prequisites

  • You should already have a consumer key, consumer secret, access token and access token secret.
    If not please go to https://www.worldoweb.co.uk/2012/create-a-twitter-app-for-the-new-api for a little guide into creating the Twitter App required for this tutorial.
  • PHP Server with CURL – I have tested it using PHP 5.3+
  • A little knowledge of PHP, CSS and how the WP themes work are beneficial but not essential.
  • This tutorial uses the tmhOAth script by Matt Harris, included in the source files.

Download the Source Files

Last Updated:2nd July 2013
Download the source files from below:


Unzip and copy the following files to WordPress Theme or WordPress Child Theme directory.

  • tmhOAuth.php
  • cacert.pem

tmhOAuth.php is a PHP authentication script to allow you to make a secure call to the twitter API.
cacert.pem enables you to access the twitter API using SSL. You can also download a copy from the following: https://curl.haxx.se/ca/cacert.pem

Adding the Function to WordPress

Now you need to add the following function to your functions.php which you will find in your theme directory. If you haven’t got one you can easily create one using a IDE or your file manager.

<?php
function display_tweets($style = '', $twitter_id, $max_tweets = 10, $is_child = false)
{
    if ($is_child) {
        require(trailingslashit(get_stylesheet_directory()) . 'tmhOAuth.php');
    } else {
        require(trailingslashit(get_template_directory()) . 'tmhOAuth.php');
    }
    
    
    $tmhOAuth = new tmhOAuth(array(
        
        'consumer_key' => 'YOUR CONSUMER KEY',
        'consumer_secret' => 'YOUR CONSUMER SECRET',
        'user_token' => 'YOUR USER TOKEN',
        'user_secret' => 'YOUR USER SECRET'
    ));
    
    
    $code    = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array(
        'screen_name' => $twitter_id,
        'count' => $max_tweets,
        'include_rts' => true,
        'include_entities' => true
    ));
    $twitter = '';
    /*Retrieves the file from cache*/
    $tweets  = get_transient('cfTweets');
    
    if ($tweets === false) { //if there is no cached file
        $t = json_decode($tmhOAuth->response['response'], true);
        set_transient('cfTweets', $t, 60 * 20); //set the file to be cached at 20 minute intervals, this can be changed
        $set_tweets = true; //setting this to true will enable you to parse and display the feed immediately
    }
    if (isset($set_tweets)) { //parse the feed just once as it will be cached from now on
        $tweets = json_decode($tmhOAuth->response['response'], true);
    }
    /*The function below is used to calculate the time since you last tweeted, used with 'time_since' parameter*/
    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);
    }
    /*Start of displaying the tweets as a list format*/
    $twitter .= '<ul id="tweeter">';
    if (!empty($tweets)) {
        foreach ($tweets as $tweet) {
            $pubDate        = $tweet['created_at'];
            $tweet          = $tweet['text'];
            $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 = preg_replace('@(https?://([-w.]+)+(:d+)?(/([w/_./-]*(?S+)?)?)?)@', '<a target="blank" title="$1" href="$1">$1</a>', $tweet);
            
            #Turn hashtags into links
            $tweet = preg_replace('/#([0-9a-zA-Z_-]+)/', "<a rel="nofollow" target='blank' title='$1' href="https://twitter.com/search?q=%23$1">#$1</a>", $tweet);
            
            #Turn @replies into links
            $tweet = preg_replace("/@([0-9a-zA-Z_-]+)/", "<a rel="nofollow" target='blank' title='$1' href="https://twitter.com/$1">@$1</a>", $tweet);
            
            
            $twitter .= "<li class='tweet'>" . $tweet . "<br />";
            
            if (isset($style)) {
                if (!empty($style)) {
                    $when = ($style == 'time_since' ? 'About' : 'On');
                    $twitter .= "<strong>" . $when . " ";
                    
                    switch ($style) {
                        case 'eng_suff': {
                            $twitter .= $english_suffix . ' ' . $full_month;
                        }
                            break;
                        case 'time_since'; {
                            $twitter .= $timeDiff . " ago";
                        }
                            break;
                        case 'ddmmyy'; {
                            $twitter .= $ddmmyy;
                        }
                            break;
                        case 'ddmm'; {
                            $twitter .= $ddmm;
                        }
                            break;
                        case 'full_date'; {
                            $twitter .= $full_date;
                        }
                            break;
                        case 'default'; {
                            $twitter .= $default;
                        }
                    } //end switch statement
                    $twitter .= "</strong></li>"; //end of List
                }
            }
        } //end of foreach
    } else {
        $twitter .= '<li>No tweets</li>';
    } //end if statement
    $twitter .= '</ul>'; //end of Unordered list (Notice it's after the foreach loop!)
    echo $twitter;
}
?>

Lines 13-16 you need to add your consumer key, consumer secret, access token and access token secret that you saved. There is more detailed explanation of the function in the source code.

Calling the function

Now you need to call the function from your theme to display your tweets. You can place it in your footer or in your sidebar. If you want to place it in a widget or blog post you will have to install a plugin that executes PHP but bear in mind that I haven’t tested this method yet!

The display_tweets function takes 4 parameters, examples below.

<?php display_tweets($style,$twitter_id,$max_tweets,$is_child);?>

$style

(String) Optional Displays the date or time since format. Leave string empty if not wanting to use a date.
The arguments are:

  • ‘eng_suff’ – Displays 6th November
  • ‘ddmm’ – Displays 06 Nov
  • ‘ddmmyy’ – Displays 06 Nov 2012
  • ‘full_date’ – Displays Tues 06 Nov 2012
  • ‘time_since’ – Displays the time since the tweet in hours, minutes etc.
  • ‘default’ – Displays November 06 2012

$twitter_id

(String) Required Your Twitter screen name (username)

$max_tweets

(int) Optional How many tweets you want to display. The default is 10.

$is_child

(boolean) Optional If your theme is a child theme then you want to set it to true. The default is false.

Examples

The default is

<?php display_tweets('','YOUR TWITTER ID');?>

If this doesn’t work try adding the true value for a child theme.

<?php display_tweets('','YOUR TWITTER ID',10,true);?>

Notice that I have set $max_tweets to 10. This is because function parameters are processed in order. Missing the 3rd value out would result in a error.

To display 20 tweets with the time since and your theme uses a child theme.

<?php display_tweets('time_since','YOUR TWITTER ID',20,true);?>

Styling our Tweets

The output will display a Unordered list which you can style easily using CSS by opening up your theme’s style.css. Here is the CSS that I use to display my tweets in my footer. You can easily change it to suit your requirements.

#tweeter /*Styles the Unordered list*/
{
    background-color:#554646;
    border:2px solid #5C5A5A;
    border-radius:10px 10px 10px 10px;
    box-shadow:4px 4px 4px 4px #252323;
    color:#FFFFFF;
    list-style:none outside none;
    margin:0;
}
.tweet /*Styles each individual tweet*/
{
    padding:10px;
}

Conclusion

If you are pretty new to PHP then you may want to stick with the defaults then use it as a basis to learn. If you have any problems or recommendations or tweaks I would love to hear them.

10 replies on “WordPress – Display your Cached Tweets using PHP and OAuth”

Avatar of LAurent

Awesome piece of code ! But i just want to put the date in French. How can i do ? Like instead of 1day ago, i want il y a un jour.

Avatar of Tracy Ridge

Ive had a look into it and managed to change most of the options apart from the time_since option. Even when I played about with the other settings I couldn’t get it to display Un instead of 1. There might be a simpler solution out there. It might be worth posting something on Stack Overflow to see if someone could help you.

Avatar of David

This is a fantastic function for something that was once simple to set up, but with 1.1 is now rather more complicated. I do have a question though. Is there easy way to turn off tweets that are replies?

Avatar of David

Great, thanks for the reply Tracey. Once I had that info, I knew where to look. Added ‘exclude_replies’ => true to the $code array.

Comments are closed.