Create a Twitter Widget with Twitter API 1.1 & PHP

Following on from my very simple tutorial on Whatever Happened to Twitters Latest Tweets? I thought that I’d compile all of the code that I have created over the last few weeks to create a quick PHP class that will allow you to show your tweets in a much cleaner and customisable way – pretty much like your own Twitter Widget.

As Twitter API has been “upgraded” to 1.1 and using oAuth we are utilising the excellent twitteroauth class in our custom class – this comes with the package so you don’t need to go grab that separately.

Our PHP Class does the following:

  • Ability to specify twitter username (to get your tweets)
  • Ability to specify number of tweets
  • Works out “Time Ago” data for each tweet
  • Links up mentions / hashtags / urls (all optional)
  • No-follow / open in new window all of these links
  • Cache the latest good tweet (in twitter.txt) in case of Twitter API Limit exceeded errors

It’s nice and simple to setup. Literally just download the folder from our Github page and then extract them to a directory on your website – for example /twitter/.

Using example.php you will see that it includes our custom class, and then using public properties we can set all of the customisation we need – including Twitter API credentials.

At the bottom of example.php you will see that the tweets are returned in an array – you can then foreach this array and echo out your tweets (and time ago) however you like.

Couple of things to make sure of:

  • Your twitter.txt is there and permission 777
  • You have entered your API credentials correctly

Again, please download the files from github and then take the code from example.php to implement it into your project.

If you think of any improvements please let me know – or simply fork the project on github!

Also if you’re after a WordPress Plugin check out our Advanced Twitter Feed Integration plugin.