Skip to content

Instantly share code, notes, and snippets.

@fastmover
Last active September 30, 2015 19:50
Show Gist options
  • Select an option

  • Save fastmover/20c8bf8b7fb3f4404975 to your computer and use it in GitHub Desktop.

Select an option

Save fastmover/20c8bf8b7fb3f4404975 to your computer and use it in GitHub Desktop.
A method for use in Wordpress for getting social share counts and cache them for an hour or specified time.
public function getShares ( $network, $url = false, $cacheTime = 3600 ) {
if( $url === false )
$url = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
$transientKey = $network . "_" . sanitize_title( $url );
$transient = get_transient( $transientKey );
if( false !== $transient )
return $transient;
switch( $network ) {
case 'twitter':
$apiURL = "http://urls.api.twitter.com/1/urls/count.json?url=";
$key = "count";
break;
case 'facebook':
$apiURL = "https://graph.facebook.com/?id=";
$key = "shares";
break;
default:
return 0;
}
$data = @file_get_contents( $apiURL . $url );
if( false === $data )
return 0;
$jsonObj = json_decode( $data );
if( isset( $jsonObj->$key ) ) {
set_transient( $transientKey, $jsonObj->$key, $cacheTime );
return $jsonObj->$key;
}
set_transient( $transientKey, 0, $cacheTime );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment