Bradley
Bradley

Reputation: 41

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.

<?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.

Upvotes: 4

Views: 1017

Answers (3)

ajknzhol
ajknzhol

Reputation: 6450

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/"); ?>

Upvotes: 1

Gabri&#235;l Ramaker
Gabri&#235;l Ramaker

Reputation: 31

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);

Upvotes: 1

citelao
citelao

Reputation: 6046

Just use Twitter's own tweet button.

It does that for you and you can style it with .twitter-share-button

(I would post this as a reply but I don't have the privilege.)

Upvotes: 1

Related Questions