2016-02-25 62 views
2

您好我有一個wp多站點,我使用Transients API來緩存社交媒體共享計數。我正在使用這裏發佈的答案:Caching custom social share count in WordPress來自Transient API Cache的不準確數據共享計數

一切正常,但它並沒有給我所有帖子的準確份額。有些人擁有正確的份額,其他人只是顯示看起來像是一個隨機數字。例如,一個有65個facebook喜歡的帖子只在添加瞬態代碼時顯示1。當我刪除瞬態時,它顯示了所有這些股票的準確數量。任何可能導致這種情況的想法?

這裏是加入的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); 
 
     
 
    \t if($cache) { 
 
      return $cache; 
 
     } 
 
    \t 
 
    \t else { 
 
    \t 
 
     $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; 
 
    \t 
 
    } 
 

 
    } 
 

 

 
    }

Everything works if I remove if($cache) { 
     return $cache; 
    } 

但隨後的網頁實在是太慢了。

我花了幾個小時試圖弄清楚,所以我想問問專家。我附上了一個屏幕截圖,比較了使用和不使用Transient API後的分享計數,以便您可以看到差異。

Comparison of Share Counts

感謝

+0

丹尼爾嗨的工作,你有沒有設法找到了利用短暫的解決方案? –

回答

0

我已經使用這個片段,並沒有爲sharecount 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; 
}