Hi I have a wp multisite where I am using the Transients API to cache social media share counts. I’m using the Answer posted here: Caching custom social share count in WordPress
Everything is working, however it is not giving me accurate share counts for all of the posts. Some have the correct share count others just show what appears to be a random number. For example a post that has 65 facebook likes only shows 1 when the Transient code is added. When I remove the Transient it shows the accurate number of shares for all of them. Any ideas of what could cause this?
Here is my code added to functions.php:
class shareCount {
private $url,$timeout;
function __construct($url,$timeout=10) {
$this->url=rawurlencode($url);
$this->timeout=$timeout;
}
function get_fb() {
$json_string = $this->file_get_contents_curl('http://api.facebook.com/restserver.php?method=links.getStats&format=json&urls='.$this->url );
$json = json_decode($json_string, true);
return isset($json[0]['total_count'])?intval($json[0]['total_count']):0;
}
private function file_get_contents_curl($url){
// Create unique transient key
$transientKey = 'sc_' + md5($url);
// Check cache
$cache = get_site_transient($transientKey);
if($cache) {
return $cache;
}
else {
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
$count = curl_exec($ch);
if(curl_error($ch))
{
die(curl_error($ch));
}
// Cache results for 1 hour
set_site_transient($transientKey, $count, 60 * 60);
return $count;
}
}
}
Everything works if I remove if($cache) {
return $cache;
}
but then the page is really slow.
I have spent hours trying to figure this out, so figured I’d ask the experts. I’ve attached a screen shot comparing the post share counts with and without the Transient API so you can see the differences.
Thanks
I have used this snippet and it did the work for sharecount api