Skip to content

Instantly share code, notes, and snippets.

@Ultrabenosaurus
Created June 24, 2013 06:57
Show Gist options
  • Save Ultrabenosaurus/5848188 to your computer and use it in GitHub Desktop.
Save Ultrabenosaurus/5848188 to your computer and use it in GitHub Desktop.
Get the count of tweets, likes and +1's for a URL. Saved from this repo - https://github.com/whyisjake/Social-Stats - but I didn't feel it deserved an actual repo so I saved it as a gist, and also added a function that returns all three stats for you. Currently relies on some WordPress functions, will need to alter that at some point.
<?php
function make_get_tweets( $url ) {
$json_string = wpcom_vip_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 make_get_likes( $url ) {
$json_string = wpcom_vip_file_get_contents('http://graph.facebook.com/?ids=' . $url);
$json = json_decode($json_string, true);
return intval( $json[$url]['shares'] );
}
function make_get_plusones( $url ) {
$args = array(
'method' => 'POST',
'headers' => array(
// setup content type to JSON
'Content-Type' => 'application/json'
),
// setup POST options to Google API
'body' => json_encode(array(
'method' => 'pos.plusones.get',
'id' => 'p',
'method' => 'pos.plusones.get',
'jsonrpc' => '2.0',
'key' => 'p',
'apiVersion' => 'v1',
'params' => array(
'nolog'=>true,
'id'=> $url,
'source'=>'widget',
'userId'=>'@viewer',
'groupId'=>'@self'
)
)),
// disable checking SSL sertificates
'sslverify'=>false
);
// retrieves JSON with HTTP POST method for current URL
$json_string = wp_remote_post( "https://clients6.google.com/rpc", $args );
if ( is_wp_error( $json_string ) ) {
// return zero if response is error
return "0";
} else {
$json = json_decode( $json_string['body'], true );
// return count of Google +1 for requsted URL
return intval( $json['result']['metadata']['globalCounts']['count'] );
}
}
function make_get_all( $url ) {
return array(
'tweets' => make_get_tweets( $url ),
'likes' => make_get_likes( $url ),
'plusones' => make_get_plusones( $url )
);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment