瞬态 API 缓存中的数据共享计数不准确


Inaccurate data share counts from Transient API Cache

嗨,我

有一个 wp 多站点,我正在使用瞬态 API 来缓存社交媒体共享计数。我正在使用此处发布的答案:在WordPress中缓存自定义社交份额计数

一切正常,但是它没有为我提供所有帖子的准确份额计数。有些具有正确的份额计数,而另一些则仅显示似乎是随机数的内容。例如,有 65 个 Facebook 赞的帖子在添加瞬态代码时仅显示 1。当我删除瞬态时,它会显示所有这些共享的准确数量。有什么想法可能导致这种情况吗?

这是我添加到函数中的代码.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;
    }

但是页面真的很慢。

我花了几个小时试图弄清楚这一点,所以我想我会问专家。我附上了一个屏幕截图,比较了使用和不使用瞬态 API 的帖子共享计数,以便您可以看到差异。

股票计数比较

谢谢

我使用了这个片段,它为共享计数 API 做了工作

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