Echo Twitter share count with PHP?

I am trying to create some text based share buttons for my WordPress that also output the shared amount. So far I got it working with Facebook and Delicious but I am not sure how to get it going with Twitter.

This is what I did for Delicious.

Read More
<?php
$shareUrl = urlencode(get_permalink($post->ID));
$shareTitle = urlencode($post->post_title);
$deliciousStats = json_decode(file_get_contents('http://feeds.delicious.com/v2/json/urlinfo/data?url='.$shareUrl));
?>

<a onclick='window.open("http://delicious.com/save?v=5&noui&jump=close&url=<?php echo $shareUrl; ?>&title=<?php echo $shareTitle; ?>", "facebook", "toolbar=no, width=550, height=550"); return false;' href='http://delicious.com/save?v=5&noui&jump=close&url=<?php echo $shareUrl; ?>&title=<?php echo $shareTitle; ?>' class='delicious'>
<?php
if($deliciousStats[0]->total_posts == 0) {
    echo 'Save';
} elseif($deliciousStats[0]->total_posts == 1) {
    echo 'One save';
} else {
    echo $deliciousStats[0]->total_posts.' saves';
}
?>
</a>

I also got the API Url which calls the tweeted numbers and URL.

http://urls.api.twitter.com/1/urls/count.json?url=SOMESITEURLHERE&callback=twttr.receiveCount

Basically it calls the JSON encoded file, and then gives you the option to share the link in <A></A> tags but instead of showing some text such as Share, it will show the count instead. I’m basically creating some CSS share buttons.

Related posts

Leave a Reply

3 comments

  1. Probably you have figured out a solution yourself by now. I just had the same problem and solved it this way:

    $handle = fopen('http://urls.api.twitter.com/1/urls/count.json?url=nu.nl', 'rb');
    $twitCount = json_decode(stream_get_contents($handle));
    fclose($handle);
    
    print_r($twitCount->count);
    
  2. function get_tweets($url) {
    
        $json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $url);
        $json = json_decode($json_string, true);
    
        return intval( $json['count'] );
    }
    
    function total($url){ 
        return get_tweets($url); }
    

    Then, use this to get the twitte share count in required place.

    <?php echo total("http://website.com/"); ?>