the graphic design blog that speaks the truth

Despite Twitter recently retiring their API v1 a few months ago, there seems to be a distinct lack of literature on the topic. Whilst browsing the internet I repeatedly see a “latest tweets” box, or similar with no data feed inside it. The cause, they are still using the old the API. Anyway, to help people migrate over to the new API and display a twitter feed correctly and robustly, I decided to write this tutorial. See below.

Stage 1 – Create a twitter API

The first thing you need to do is set up a twitter API by logging into your twitter account here.

create-a-twitter-application

Once logged in, you will be presented with a screen that looks similar to the above. Create your application by filling in the following fields as a minimum:

Name: Your application name. This is used to attribute the source of a tweet and in user-facing authorization screens. 32 characters max.” – This field can be anything you want, but try to avoid entering generic names like “My Tweets” for example.

Description: Your application description, which will be shown in user-facing authorization screens. Between 10 and 200 characters max.” – Again, this can be anything you want, but try to avoid generic descriptions.

Website: Your application’s publicly accessible home page, where users can go to download, make use of, or find out more information about your application. This fully-qualified URL is used in the source attribution for tweets created by your application and will be shown in user-facing authorization screens.” – You can enter any website you like here, it doesn’t have to be the website you are adding your tweet timeline too, it would make sense to add that in here though. Just remember to include the “http://” part of the URL else the page will spit out an error message.

For the purpose of this tutorial you can leave the “Callback URL” field blank. Agree to the terms & conditions, enter the captcha and proceed to click the “Create your Twitter application” button.

Stage 2 – Configure Our New Application

This next section is where the majority of tutorials fail and where the majority of users have problems. It is vital that we configure our new application to have the top level permissions. Once you have created your new application you will be taken to a screen that looks similar to the image below.

twitter-feed-API-permissions

Notice that the current “Access Level” for our application is set to be “Read-only“. If we don’t change this, our twitter feed will not work. To do so, scroll back up to the top of the page and click the “Settings” tab. Scroll down to the middle of the page until you reach the “Application Type” area that looks something like this:

twitter-feed-application-type

Once there, you need to check the box next to “Read, Write and Access direct messages“, scroll down to the bottom of the page and click the “Update this twitter application’s settings” button. This page can sometimes be a little buggy. So once done, scroll back up the page and check that the setting has been changed. You may need to retry 2 or 3 times until it takes affect.

When done, navigate back to the “Details” tab and check that our new applications have indeed been updated to the permission level “Read, write, and direct messages” underneath the “OAuth settings” area. If they have not, go back to the previous page and complete the steps again.

Stage 2.1 – Create Your Access Token

The next stage is to create an “Access Token” for your twitter feed application. Presuming the above has all been completed correctly, and staying on the “Details” tab, scroll down to the bottom of the page and click the “Create my access token” button. Again, this can sometimes be a little temperamental so continue to click it until your access token details appear just above this button.

NOTE: If you have completed the steps above correctly, your access token should have the access level of “Read, write, and direct messages“.

Stage 3 – The Code

Include jQuery

The first step is to include jQuery (yes you need this) if you haven’t already:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js" type="text/javascript"></script>

Notice here, I am linking to a google hosted (always better that self hosted) version of jQuery, and notably, it is version 1.8.1.

NOTE: This script is known to have difficulty with jQuery versions of 1.9 and above.

Include Our Custom jQuery File

We then need to include the link to the javascript file that will do the bulk of the work for us:

<script type="text/javascript" src="/js/mytweets.js"></script>

Of course, this is a relative file path, and you should always ensure that the correct file paths are given.

The custom File Code

Copy the contents of this file into a file named “mytweets.js” and change the following settings:

User: Enter your twitter username in here

numTweets: The amount of tweets to show

appendTo: Enter the ID or Class of the div you want the tweets to appear inside. Remembering to add either a “#” or a “.” respectively.

The final change you need to make to this file is to this section:

$.ajax({
            url: 'grabtweets.php',
            type: 'POST',
            dataType: 'json',
            data: request,

You simply need to change the url to the path where “grabtweets.php is stored on your server. Once done, save the file and upload it to the location you specified in the script tag above.

Grabtweets.php

Next, you need to copy the code below into a file named “grabtweets.php

<? require_once ('codebird.php'); 
$CONSUMER_KEY = 'CONSUMER KEY IN HERE';     
$CONSUMER_SECRET = 'CONSUMER SECRET IN HERE';     
$ACCESS_TOKEN = 'ACCESS TOKEN IN HERE';     
$ACCESS_TOKEN_SECRET = 'ACCESS TOKEN SECRET IN HERE';       
Codebird::setConsumerKey($CONSUMER_KEY, $CONSUMER_SECRET);     
$cb = Codebird::getInstance();     
$cb->setToken($ACCESS_TOKEN, $ACCESS_TOKEN_SECRET);
//retrieve posts
$q = $_POST['q'];
$count = $_POST['count'];
$api = $_POST['api'];
//https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
//https://dev.twitter.com/docs/api/1.1/get/search/tweets
$params = array(
'screen_name' => $q,
'q' => $q,
'count' => $count
);
//Make the REST call
$data = (array) $cb->$api($params);
//Output result in JSON, getting it ready for jQuery to process
echo json_encode($data);
?>

Now we need to head back to our Twitter Application, and click on the “OAuth Tool” tab. Here you will see the four fields that will contain our consumer and access codes, similar to the image below:

twitter-feed-keysCopy the codes from this page into the corresponding fields in “grabtweets.php“. When done, upload the file to the location on your server you referred into in the “mytweets.js” file.

Codebird.php

We are almost there! One more task though. Third party applications that interact with the new Twitter API require API requests to authenticated. Luckily, there is a very good service that does this for us. To do so, simply download this file, unzip it and upload “codebird.php” to the location you referred to above in “grabtweets.php“. Go back to your website, you should now see the latest tweet(s) in the element you defined!

Hope that helps someone out!

ABOUT THE AUTHOR

SHARE THIS ARTICLE

  1. 24/08/13
    2:21 am
    Great help!!... even in Twitter its kinda tricky to understand hehe. thanks!
  2. 05/10/13
    3:27 am
    HI Daniel, I followed the tutorial and it worked great, but whenever I put a date or a URL it display funky text. How I get it to just display exactly what I tweeted. For example: I used the word "don't" and it link it to some guy with a user name of @Don. How I get it to stop doing that? Thanks
  3. 07/10/13
    9:40 am
    Hi Lucy, Thanks for the reply. This needed an update to the "ify" function that "cleans" the tweets. Try re-downloading the "mytweets" file and it should be working correctly now.
  4. 08/10/13
    11:16 am
    Hi Daniel Thanks for the great tutorial just what i am looking for, is there any way to order tweets in date ascending order??
  5. 10/10/13
    11:49 am
    Thanks Stuart, Unfortunately as far as I am aware, there is no way to do this.
  6. 16/06/14
    12:24 pm
    Hello I can tell you how to fix the jquery version problem. It is very simple yaar. With any jquery version 1.9 upwards, the mytweets.js code is breaking at the timeAgo plugin code inside the file. Just replace: if ($.browser.msie) { with: if (navigator.userAgent.toLowerCase().indexOf('msie 6') != -1) { Then all will be fixed. Thankyou
  7. 25/08/14
    11:06 am
    Hi Deniel Thanks for posting. I want to know that is it working with current version of twitter? i am getting issue to access post with same code as you describe. I am not getting which page is asking issue. Array ( [errors] => Array ( [0] => stdClass Object ( [message] => Sorry, that page does not exist [code] => 34 ) ) [httpstatus] => 404 ) Thanks waiting in reply Brijmohan
  8. 01/12/14
    3:26 pm
    Thanx for the tut :D Got it working faster than you can say Twitter :D Just tryifng to figure out how to change the color/layout a bit with CSS. Inspecting the elements let's me know what element is called what :)
  9. 05/10/15
    7:13 am
    i want to show the Image with the tweets as well. can you Please help me out with this issue?
  10. 29/05/16
    2:39 am
    Hey PIYA, this thread is old but I just worked through this tutorial tonight and wanted to share a solution for anyone looking to fix the image reference. In the "mytweets.js" file go to the line that says: .replace('{IMG}', img) and change it to .replace('{IMG}', data[i].user.profile_image_url)
  11. 27/07/16
    8:59 am
    Please can you send complete files as one zip... Thanks
  12. 12/10/16
    7:47 pm
    Kam
    I'm trying to get this working but finding I get a 500 error status when I try to load the .php via the JS file you've created. I've tried accessing the .php file directly and get the same error - but the URL etc is correct and I can't see where this is going wrong. Error: http://www.website.com/wp-content/themes/themename/tweets.php?callback=jQuery112408327882372920851_1476301186914&q=website&count=5&api=statuses_userTimeline&_=1476301186915 Failed to load resource: the server responded with a status of 500 (Internal Server Error)
  13. 12/10/16
    8:04 pm
    Kam
    Just managed to get errors displaying in the .php file: Notice: Undefined index: q in /home/sites/website.com/public_html/wp-content/themes/website/tweets.php on line 16 The 'q' is in the .php file that you've created that uploads to the website
  14. 12/12/16
    6:56 am
    I delight in, cause I discovered exactly what I was having a look for. You have ended my four day lengthy hunt! God Bless you man. Have a great day. Bye
  15. 14/12/16
    6:36 pm
    Your methpd of describimg thee whole thing in this post is truly pleasant, alll be able to without difficulty know it, Thanks a lot. Feel free too visit my blog post: παπουτσια nak
  16. 02/01/17
    6:13 pm
    My coder is trying to convince me to move to .net from PHP. I have always disliked the idea because of the expenses. But he's tryiong none the less. I've been using WordPress on several websites for about a year and am nervous about switching to another platform. I have heard great things about blogengine.net. Is there a way I can transfer all my wordpress content into it? Any help would be really appreciated!
Voice Your Opinion

Thanks for your comment, it will appear here once it has been moderated.