2014-09-04 48 views
2

我真的很喜歡在我的博文中有分享計數器。我注意到它實際上鼓勵訪問者自己分享內容。由於沒有WordPress的sharecount插件,我真的覺得很滿意(其中大多數都讓位給很多電話),所以我自己編寫了代碼。在WordPress中緩存自定義社交分享數

它工作完美,但仍然減緩我的網站。所以我寧願緩存,每小時刷新一次左右。我不知道如何管理這個雖然...任何想法?

這是我放在主題功能文件:

class shareCount { 
private $url,$timeout; 
function __construct($url,$timeout=10) { 
$this->url=rawurlencode($url); 
$this->timeout=$timeout; 
} 

function get_tweets() { 
$json_string = $this->file_get_contents_curl('http://urls.api.twitter.com/1/urls/count.json?url=' . $this->url); 
$json = json_decode($json_string, true); 
return isset($json['count'])?intval($json['count']):0; 
} 

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){ 
$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); 
$cont = curl_exec($ch); 
if(curl_error($ch)) 
    { 
     die(curl_error($ch)); 
    } 
     return $cont; 
    } 

}

這是我在single.php中使用:

<!-- Begin mod: Add share counter --> 
<span class="share-count"> 
    <?php 
    $obj=new shareCount(get_permalink($post->ID)); 
    echo $obj->get_tweets() + $obj->get_fb(); 
    ?> 
</span> 
<span class="share-text"> 
    keer gedeeld 
</span> 
<!-- End mod: Add share counter --> 

然後,我還加了一些CSS。

+0

您可以查看Transients API以臨時緩存共享計數。請參閱:http://codex.wordpress.org/Transients_API – vicente 2014-12-04 16:18:45

回答

0

像vicente說的,你應該使用內置的瞬態緩存。

private function file_get_contents_curl($url){ 
    // Create unique transient key 
    $transientKey = 'sc_' + md5($url); 

    // Check cache 
    $cache = get_transient($transientKey); 
    if($cache) { 
     return $cache; 
    } 

    $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); 
    $cont = curl_exec($ch); 
    if(curl_error($ch)) 
    { 
     die(curl_error($ch)); 
    } 

    // Cache results for 1 hour 
    set_transient($transientKey, $cont, 60*60); 

    return $cont; 
}