Skip to content

Instantly share code, notes, and snippets.

@bearded-avenger
Created December 19, 2013 16:04
Show Gist options
  • Save bearded-avenger/8041668 to your computer and use it in GitHub Desktop.
Save bearded-avenger/8041668 to your computer and use it in GitHub Desktop.
Get total share counts of a Wordpress post and cache with transient.
function aesop_share_count(){
$post_id = get_the_ID();
//$url = 'http://nickhaskins.co'; // this one used for testing to return a working result
$url = get_permalink();
$apiurl = sprintf('http://api.sharedcount.com/?url=%s',$url);
$transientKey = 'AesopShareCounts'. (int) $post_id;
$cached = get_transient($transientKey);
if (false !== $cached) {
return $cached;
}
$fetch = wp_remote_get($apiurl, array('sslverify'=>false));
$remote = wp_remote_retrieve_body($fetch);
if( !is_wp_error( $remote ) ) {
$count = json_decode( $remote,true);
}
$twitter = $count['Twitter'];
$fb_like = $count['Facebook']['like_count'];
$total = $fb_like + $twitter;
$out = sprintf('%s',$total);
set_transient($transientKey, $out, 600);
return $out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment