我真的很喜欢在我的博客上使用分享计数器。我注意到它实际上鼓励访问者自己分享内容。因为那里没有WordPress sharecount插件,我实际上觉得很满意(大部分都让位于很多调用),我自己编写代码。
它完美无缺,但仍然减慢了我的网站速度。所以我宁愿每小时缓存和刷新一次左右。我不知道怎么管理这个......有什么想法吗?
这是我在主题函数文件中添加的内容:
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 :(得分:0)
像维森特所说,你应该使用内置的瞬态缓存。
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;
}