Maybe you don't know that you can get the retweet count for a given URL using only the Twitter's API. In this article we'll see how to achieve this result by using jQuery and a little help from PHP.
The base Twitter's API URL is as follows:
http://urls.api.twitter.com/1/urls/count.json?url=
The url
parameter is a valid full URL. The returned JSON object has a count
property which contains the number of retweets for the provided URL.
First we need a PHP proxy to fetch the remote JSON file:
<?php
header('Content-Type: application/json');
$url = $_GET['url'];
if(filter_var($url, FILTER_VALIDATE_URL)) {
$baseURL = 'http://urls.api.twitter.com/1/urls/count.json?url=';
$json = file_get_contents($baseURL . $url);
echo $json;
}
exit();
?>
Then we can use jQuery:
$(function() {
var button = $('#get'),
output = $('#count');
button.on('click', function() {
var url = 'http://coding.smashingmagazine.com/2013/02/27/css-form-elements-problem/';
$.getJSON('twitter-url.php', { url: url }, function(json) {
output.text(json.count);
});
});
});
You can see the example in the following video.