How many times has an URL been tweeted?

You may have noticed how some websites let you know how many times URLs have been tweeted. How do they do that? The twitter api will help.

The the call we need is:

http://urls.api.twitter.com/1/urls/count.json

This call takes a url as a parameter. Let’s look at an example:

http://urls.api.twitter.com/1/urls/count.json?url=www.phptherightway.com/

This returns the following JSON (as of the time of writing), which we can parse to get the number we want:

{"count":5154,"url":"http:\/\/www.phptherightway.com\/"}

With jQuery

The following snippet uses jQuery’s $.getJSON method to call the twitter api using JSONP. Wire it up, define your callbacks and you’re away.

$.getJSON(
    "http://urls.api.twitter.com/1/urls/count.json",
    "callback=?&url="+encodeURIComponent("www.example.com"))
 .done( callbackSuccess )
 .fail( callbackError );

Example

The page www.phptherightway.com has been tweeted 5154 times.

Read more

Find out more:

Tags: